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/VE.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.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1460       llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1461                                                    Cmd.getArguments()))
1462     return;
1463 
1464   std::string TmpName = GetTemporaryPath("response", "txt");
1465   Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1466 }
1467 
1468 int Driver::ExecuteCompilation(
1469     Compilation &C,
1470     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1471   // Just print if -### was present.
1472   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1473     C.getJobs().Print(llvm::errs(), "\n", true);
1474     return 0;
1475   }
1476 
1477   // If there were errors building the compilation, quit now.
1478   if (Diags.hasErrorOccurred())
1479     return 1;
1480 
1481   // Set up response file names for each command, if necessary
1482   for (auto &Job : C.getJobs())
1483     setUpResponseFiles(C, Job);
1484 
1485   C.ExecuteJobs(C.getJobs(), FailingCommands);
1486 
1487   // If the command succeeded, we are done.
1488   if (FailingCommands.empty())
1489     return 0;
1490 
1491   // Otherwise, remove result files and print extra information about abnormal
1492   // failures.
1493   int Res = 0;
1494   for (const auto &CmdPair : FailingCommands) {
1495     int CommandRes = CmdPair.first;
1496     const Command *FailingCommand = CmdPair.second;
1497 
1498     // Remove result files if we're not saving temps.
1499     if (!isSaveTempsEnabled()) {
1500       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1501       C.CleanupFileMap(C.getResultFiles(), JA, true);
1502 
1503       // Failure result files are valid unless we crashed.
1504       if (CommandRes < 0)
1505         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1506     }
1507 
1508 #if LLVM_ON_UNIX
1509     // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1510     // for SIGPIPE. Do not print diagnostics for this case.
1511     if (CommandRes == EX_IOERR) {
1512       Res = CommandRes;
1513       continue;
1514     }
1515 #endif
1516 
1517     // Print extra information about abnormal failures, if possible.
1518     //
1519     // This is ad-hoc, but we don't want to be excessively noisy. If the result
1520     // status was 1, assume the command failed normally. In particular, if it
1521     // was the compiler then assume it gave a reasonable error code. Failures
1522     // in other tools are less common, and they generally have worse
1523     // diagnostics, so always print the diagnostic there.
1524     const Tool &FailingTool = FailingCommand->getCreator();
1525 
1526     if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1527       // FIXME: See FIXME above regarding result code interpretation.
1528       if (CommandRes < 0)
1529         Diag(clang::diag::err_drv_command_signalled)
1530             << FailingTool.getShortName();
1531       else
1532         Diag(clang::diag::err_drv_command_failed)
1533             << FailingTool.getShortName() << CommandRes;
1534     }
1535   }
1536   return Res;
1537 }
1538 
1539 void Driver::PrintHelp(bool ShowHidden) const {
1540   unsigned IncludedFlagsBitmask;
1541   unsigned ExcludedFlagsBitmask;
1542   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1543       getIncludeExcludeOptionFlagMasks(IsCLMode());
1544 
1545   ExcludedFlagsBitmask |= options::NoDriverOption;
1546   if (!ShowHidden)
1547     ExcludedFlagsBitmask |= HelpHidden;
1548 
1549   std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1550   getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1551                       IncludedFlagsBitmask, ExcludedFlagsBitmask,
1552                       /*ShowAllAliases=*/false);
1553 }
1554 
1555 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1556   // FIXME: The following handlers should use a callback mechanism, we don't
1557   // know what the client would like to do.
1558   OS << getClangFullVersion() << '\n';
1559   const ToolChain &TC = C.getDefaultToolChain();
1560   OS << "Target: " << TC.getTripleString() << '\n';
1561 
1562   // Print the threading model.
1563   if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1564     // Don't print if the ToolChain would have barfed on it already
1565     if (TC.isThreadModelSupported(A->getValue()))
1566       OS << "Thread model: " << A->getValue();
1567   } else
1568     OS << "Thread model: " << TC.getThreadModel();
1569   OS << '\n';
1570 
1571   // Print out the install directory.
1572   OS << "InstalledDir: " << InstalledDir << '\n';
1573 
1574   // If configuration file was used, print its path.
1575   if (!ConfigFile.empty())
1576     OS << "Configuration file: " << ConfigFile << '\n';
1577 }
1578 
1579 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1580 /// option.
1581 static void PrintDiagnosticCategories(raw_ostream &OS) {
1582   // Skip the empty category.
1583   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1584        ++i)
1585     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1586 }
1587 
1588 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1589   if (PassedFlags == "")
1590     return;
1591   // Print out all options that start with a given argument. This is used for
1592   // shell autocompletion.
1593   std::vector<std::string> SuggestedCompletions;
1594   std::vector<std::string> Flags;
1595 
1596   unsigned short DisableFlags =
1597       options::NoDriverOption | options::Unsupported | options::Ignored;
1598 
1599   // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1600   // because the latter indicates that the user put space before pushing tab
1601   // which should end up in a file completion.
1602   const bool HasSpace = PassedFlags.endswith(",");
1603 
1604   // Parse PassedFlags by "," as all the command-line flags are passed to this
1605   // function separated by ","
1606   StringRef TargetFlags = PassedFlags;
1607   while (TargetFlags != "") {
1608     StringRef CurFlag;
1609     std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1610     Flags.push_back(std::string(CurFlag));
1611   }
1612 
1613   // We want to show cc1-only options only when clang is invoked with -cc1 or
1614   // -Xclang.
1615   if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1616     DisableFlags &= ~options::NoDriverOption;
1617 
1618   const llvm::opt::OptTable &Opts = getOpts();
1619   StringRef Cur;
1620   Cur = Flags.at(Flags.size() - 1);
1621   StringRef Prev;
1622   if (Flags.size() >= 2) {
1623     Prev = Flags.at(Flags.size() - 2);
1624     SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
1625   }
1626 
1627   if (SuggestedCompletions.empty())
1628     SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
1629 
1630   // If Flags were empty, it means the user typed `clang [tab]` where we should
1631   // list all possible flags. If there was no value completion and the user
1632   // pressed tab after a space, we should fall back to a file completion.
1633   // We're printing a newline to be consistent with what we print at the end of
1634   // this function.
1635   if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1636     llvm::outs() << '\n';
1637     return;
1638   }
1639 
1640   // When flag ends with '=' and there was no value completion, return empty
1641   // string and fall back to the file autocompletion.
1642   if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1643     // If the flag is in the form of "--autocomplete=-foo",
1644     // we were requested to print out all option names that start with "-foo".
1645     // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1646     SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
1647 
1648     // We have to query the -W flags manually as they're not in the OptTable.
1649     // TODO: Find a good way to add them to OptTable instead and them remove
1650     // this code.
1651     for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1652       if (S.startswith(Cur))
1653         SuggestedCompletions.push_back(std::string(S));
1654   }
1655 
1656   // Sort the autocomplete candidates so that shells print them out in a
1657   // deterministic order. We could sort in any way, but we chose
1658   // case-insensitive sorting for consistency with the -help option
1659   // which prints out options in the case-insensitive alphabetical order.
1660   llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1661     if (int X = A.compare_lower(B))
1662       return X < 0;
1663     return A.compare(B) > 0;
1664   });
1665 
1666   llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1667 }
1668 
1669 bool Driver::HandleImmediateArgs(const Compilation &C) {
1670   // The order these options are handled in gcc is all over the place, but we
1671   // don't expect inconsistencies w.r.t. that to matter in practice.
1672 
1673   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1674     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1675     return false;
1676   }
1677 
1678   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1679     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1680     // return an answer which matches our definition of __VERSION__.
1681     llvm::outs() << CLANG_VERSION_STRING << "\n";
1682     return false;
1683   }
1684 
1685   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1686     PrintDiagnosticCategories(llvm::outs());
1687     return false;
1688   }
1689 
1690   if (C.getArgs().hasArg(options::OPT_help) ||
1691       C.getArgs().hasArg(options::OPT__help_hidden)) {
1692     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1693     return false;
1694   }
1695 
1696   if (C.getArgs().hasArg(options::OPT__version)) {
1697     // Follow gcc behavior and use stdout for --version and stderr for -v.
1698     PrintVersion(C, llvm::outs());
1699     return false;
1700   }
1701 
1702   if (C.getArgs().hasArg(options::OPT_v) ||
1703       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
1704       C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
1705     PrintVersion(C, llvm::errs());
1706     SuppressMissingInputWarning = true;
1707   }
1708 
1709   if (C.getArgs().hasArg(options::OPT_v)) {
1710     if (!SystemConfigDir.empty())
1711       llvm::errs() << "System configuration file directory: "
1712                    << SystemConfigDir << "\n";
1713     if (!UserConfigDir.empty())
1714       llvm::errs() << "User configuration file directory: "
1715                    << UserConfigDir << "\n";
1716   }
1717 
1718   const ToolChain &TC = C.getDefaultToolChain();
1719 
1720   if (C.getArgs().hasArg(options::OPT_v))
1721     TC.printVerboseInfo(llvm::errs());
1722 
1723   if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1724     llvm::outs() << ResourceDir << '\n';
1725     return false;
1726   }
1727 
1728   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1729     llvm::outs() << "programs: =";
1730     bool separator = false;
1731     for (const std::string &Path : TC.getProgramPaths()) {
1732       if (separator)
1733         llvm::outs() << llvm::sys::EnvPathSeparator;
1734       llvm::outs() << Path;
1735       separator = true;
1736     }
1737     llvm::outs() << "\n";
1738     llvm::outs() << "libraries: =" << ResourceDir;
1739 
1740     StringRef sysroot = C.getSysRoot();
1741 
1742     for (const std::string &Path : TC.getFilePaths()) {
1743       // Always print a separator. ResourceDir was the first item shown.
1744       llvm::outs() << llvm::sys::EnvPathSeparator;
1745       // Interpretation of leading '=' is needed only for NetBSD.
1746       if (Path[0] == '=')
1747         llvm::outs() << sysroot << Path.substr(1);
1748       else
1749         llvm::outs() << Path;
1750     }
1751     llvm::outs() << "\n";
1752     return false;
1753   }
1754 
1755   // FIXME: The following handlers should use a callback mechanism, we don't
1756   // know what the client would like to do.
1757   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1758     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1759     return false;
1760   }
1761 
1762   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1763     StringRef ProgName = A->getValue();
1764 
1765     // Null program name cannot have a path.
1766     if (! ProgName.empty())
1767       llvm::outs() << GetProgramPath(ProgName, TC);
1768 
1769     llvm::outs() << "\n";
1770     return false;
1771   }
1772 
1773   if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1774     StringRef PassedFlags = A->getValue();
1775     HandleAutocompletions(PassedFlags);
1776     return false;
1777   }
1778 
1779   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1780     ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1781     const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1782     RegisterEffectiveTriple TripleRAII(TC, Triple);
1783     switch (RLT) {
1784     case ToolChain::RLT_CompilerRT:
1785       llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1786       break;
1787     case ToolChain::RLT_Libgcc:
1788       llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1789       break;
1790     }
1791     return false;
1792   }
1793 
1794   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1795     for (const Multilib &Multilib : TC.getMultilibs())
1796       llvm::outs() << Multilib << "\n";
1797     return false;
1798   }
1799 
1800   if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1801     const Multilib &Multilib = TC.getMultilib();
1802     if (Multilib.gccSuffix().empty())
1803       llvm::outs() << ".\n";
1804     else {
1805       StringRef Suffix(Multilib.gccSuffix());
1806       assert(Suffix.front() == '/');
1807       llvm::outs() << Suffix.substr(1) << "\n";
1808     }
1809     return false;
1810   }
1811 
1812   if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1813     llvm::outs() << TC.getTripleString() << "\n";
1814     return false;
1815   }
1816 
1817   if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1818     const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1819     llvm::outs() << Triple.getTriple() << "\n";
1820     return false;
1821   }
1822 
1823   if (C.getArgs().hasArg(options::OPT_print_targets)) {
1824     llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
1825     return false;
1826   }
1827 
1828   return true;
1829 }
1830 
1831 enum {
1832   TopLevelAction = 0,
1833   HeadSibAction = 1,
1834   OtherSibAction = 2,
1835 };
1836 
1837 // Display an action graph human-readably.  Action A is the "sink" node
1838 // and latest-occuring action. Traversal is in pre-order, visiting the
1839 // inputs to each action before printing the action itself.
1840 static unsigned PrintActions1(const Compilation &C, Action *A,
1841                               std::map<Action *, unsigned> &Ids,
1842                               Twine Indent = {}, int Kind = TopLevelAction) {
1843   if (Ids.count(A)) // A was already visited.
1844     return Ids[A];
1845 
1846   std::string str;
1847   llvm::raw_string_ostream os(str);
1848 
1849   auto getSibIndent = [](int K) -> Twine {
1850     return (K == HeadSibAction) ? "   " : (K == OtherSibAction) ? "|  " : "";
1851   };
1852 
1853   Twine SibIndent = Indent + getSibIndent(Kind);
1854   int SibKind = HeadSibAction;
1855   os << Action::getClassName(A->getKind()) << ", ";
1856   if (InputAction *IA = dyn_cast<InputAction>(A)) {
1857     os << "\"" << IA->getInputArg().getValue() << "\"";
1858   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1859     os << '"' << BIA->getArchName() << '"' << ", {"
1860        << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
1861   } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1862     bool IsFirst = true;
1863     OA->doOnEachDependence(
1864         [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1865           assert(TC && "Unknown host toolchain");
1866           // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1867           // sm_35 this will generate:
1868           // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1869           // (nvptx64-nvidia-cuda:sm_35) {#ID}
1870           if (!IsFirst)
1871             os << ", ";
1872           os << '"';
1873           os << A->getOffloadingKindPrefix();
1874           os << " (";
1875           os << TC->getTriple().normalize();
1876           if (BoundArch)
1877             os << ":" << BoundArch;
1878           os << ")";
1879           os << '"';
1880           os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
1881           IsFirst = false;
1882           SibKind = OtherSibAction;
1883         });
1884   } else {
1885     const ActionList *AL = &A->getInputs();
1886 
1887     if (AL->size()) {
1888       const char *Prefix = "{";
1889       for (Action *PreRequisite : *AL) {
1890         os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
1891         Prefix = ", ";
1892         SibKind = OtherSibAction;
1893       }
1894       os << "}";
1895     } else
1896       os << "{}";
1897   }
1898 
1899   // Append offload info for all options other than the offloading action
1900   // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1901   std::string offload_str;
1902   llvm::raw_string_ostream offload_os(offload_str);
1903   if (!isa<OffloadAction>(A)) {
1904     auto S = A->getOffloadingKindPrefix();
1905     if (!S.empty()) {
1906       offload_os << ", (" << S;
1907       if (A->getOffloadingArch())
1908         offload_os << ", " << A->getOffloadingArch();
1909       offload_os << ")";
1910     }
1911   }
1912 
1913   auto getSelfIndent = [](int K) -> Twine {
1914     return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
1915   };
1916 
1917   unsigned Id = Ids.size();
1918   Ids[A] = Id;
1919   llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
1920                << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1921 
1922   return Id;
1923 }
1924 
1925 // Print the action graphs in a compilation C.
1926 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1927 void Driver::PrintActions(const Compilation &C) const {
1928   std::map<Action *, unsigned> Ids;
1929   for (Action *A : C.getActions())
1930     PrintActions1(C, A, Ids);
1931 }
1932 
1933 /// Check whether the given input tree contains any compilation or
1934 /// assembly actions.
1935 static bool ContainsCompileOrAssembleAction(const Action *A) {
1936   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1937       isa<AssembleJobAction>(A))
1938     return true;
1939 
1940   for (const Action *Input : A->inputs())
1941     if (ContainsCompileOrAssembleAction(Input))
1942       return true;
1943 
1944   return false;
1945 }
1946 
1947 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1948                                    const InputList &BAInputs) const {
1949   DerivedArgList &Args = C.getArgs();
1950   ActionList &Actions = C.getActions();
1951   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1952   // Collect the list of architectures. Duplicates are allowed, but should only
1953   // be handled once (in the order seen).
1954   llvm::StringSet<> ArchNames;
1955   SmallVector<const char *, 4> Archs;
1956   for (Arg *A : Args) {
1957     if (A->getOption().matches(options::OPT_arch)) {
1958       // Validate the option here; we don't save the type here because its
1959       // particular spelling may participate in other driver choices.
1960       llvm::Triple::ArchType Arch =
1961           tools::darwin::getArchTypeForMachOArchName(A->getValue());
1962       if (Arch == llvm::Triple::UnknownArch) {
1963         Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1964         continue;
1965       }
1966 
1967       A->claim();
1968       if (ArchNames.insert(A->getValue()).second)
1969         Archs.push_back(A->getValue());
1970     }
1971   }
1972 
1973   // When there is no explicit arch for this platform, make sure we still bind
1974   // the architecture (to the default) so that -Xarch_ is handled correctly.
1975   if (!Archs.size())
1976     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1977 
1978   ActionList SingleActions;
1979   BuildActions(C, Args, BAInputs, SingleActions);
1980 
1981   // Add in arch bindings for every top level action, as well as lipo and
1982   // dsymutil steps if needed.
1983   for (Action* Act : SingleActions) {
1984     // Make sure we can lipo this kind of output. If not (and it is an actual
1985     // output) then we disallow, since we can't create an output file with the
1986     // right name without overwriting it. We could remove this oddity by just
1987     // changing the output names to include the arch, which would also fix
1988     // -save-temps. Compatibility wins for now.
1989 
1990     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1991       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1992           << types::getTypeName(Act->getType());
1993 
1994     ActionList Inputs;
1995     for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1996       Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1997 
1998     // Lipo if necessary, we do it this way because we need to set the arch flag
1999     // so that -Xarch_ gets overwritten.
2000     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2001       Actions.append(Inputs.begin(), Inputs.end());
2002     else
2003       Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2004 
2005     // Handle debug info queries.
2006     Arg *A = Args.getLastArg(options::OPT_g_Group);
2007     bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2008                             !A->getOption().matches(options::OPT_gstabs);
2009     if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2010         ContainsCompileOrAssembleAction(Actions.back())) {
2011 
2012       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2013       // have a compile input. We need to run 'dsymutil' ourselves in such cases
2014       // because the debug info will refer to a temporary object file which
2015       // will be removed at the end of the compilation process.
2016       if (Act->getType() == types::TY_Image) {
2017         ActionList Inputs;
2018         Inputs.push_back(Actions.back());
2019         Actions.pop_back();
2020         Actions.push_back(
2021             C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2022       }
2023 
2024       // Verify the debug info output.
2025       if (Args.hasArg(options::OPT_verify_debug_info)) {
2026         Action* LastAction = Actions.back();
2027         Actions.pop_back();
2028         Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2029             LastAction, types::TY_Nothing));
2030       }
2031     }
2032   }
2033 }
2034 
2035 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2036                                     types::ID Ty, bool TypoCorrect) const {
2037   if (!getCheckInputsExist())
2038     return true;
2039 
2040   // stdin always exists.
2041   if (Value == "-")
2042     return true;
2043 
2044   if (getVFS().exists(Value))
2045     return true;
2046 
2047   if (IsCLMode()) {
2048     if (!llvm::sys::path::is_absolute(Twine(Value)) &&
2049         llvm::sys::Process::FindInEnvPath("LIB", Value))
2050       return true;
2051 
2052     if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
2053       // Arguments to the /link flag might cause the linker to search for object
2054       // and library files in paths we don't know about. Don't error in such
2055       // cases.
2056       return true;
2057     }
2058   }
2059 
2060   if (TypoCorrect) {
2061     // Check if the filename is a typo for an option flag. OptTable thinks
2062     // that all args that are not known options and that start with / are
2063     // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2064     // the option `/diagnostics:caret` than a reference to a file in the root
2065     // directory.
2066     unsigned IncludedFlagsBitmask;
2067     unsigned ExcludedFlagsBitmask;
2068     std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2069         getIncludeExcludeOptionFlagMasks(IsCLMode());
2070     std::string Nearest;
2071     if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2072                               ExcludedFlagsBitmask) <= 1) {
2073       Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2074           << Value << Nearest;
2075       return false;
2076     }
2077   }
2078 
2079   Diag(clang::diag::err_drv_no_such_file) << Value;
2080   return false;
2081 }
2082 
2083 // Construct a the list of inputs and their types.
2084 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2085                          InputList &Inputs) const {
2086   const llvm::opt::OptTable &Opts = getOpts();
2087   // Track the current user specified (-x) input. We also explicitly track the
2088   // argument used to set the type; we only want to claim the type when we
2089   // actually use it, so we warn about unused -x arguments.
2090   types::ID InputType = types::TY_Nothing;
2091   Arg *InputTypeArg = nullptr;
2092 
2093   // The last /TC or /TP option sets the input type to C or C++ globally.
2094   if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2095                                          options::OPT__SLASH_TP)) {
2096     InputTypeArg = TCTP;
2097     InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2098                     ? types::TY_C
2099                     : types::TY_CXX;
2100 
2101     Arg *Previous = nullptr;
2102     bool ShowNote = false;
2103     for (Arg *A :
2104          Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2105       if (Previous) {
2106         Diag(clang::diag::warn_drv_overriding_flag_option)
2107           << Previous->getSpelling() << A->getSpelling();
2108         ShowNote = true;
2109       }
2110       Previous = A;
2111     }
2112     if (ShowNote)
2113       Diag(clang::diag::note_drv_t_option_is_global);
2114 
2115     // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2116     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2117   }
2118 
2119   for (Arg *A : Args) {
2120     if (A->getOption().getKind() == Option::InputClass) {
2121       const char *Value = A->getValue();
2122       types::ID Ty = types::TY_INVALID;
2123 
2124       // Infer the input type if necessary.
2125       if (InputType == types::TY_Nothing) {
2126         // If there was an explicit arg for this, claim it.
2127         if (InputTypeArg)
2128           InputTypeArg->claim();
2129 
2130         // stdin must be handled specially.
2131         if (memcmp(Value, "-", 2) == 0) {
2132           // If running with -E, treat as a C input (this changes the builtin
2133           // macros, for example). This may be overridden by -ObjC below.
2134           //
2135           // Otherwise emit an error but still use a valid type to avoid
2136           // spurious errors (e.g., no inputs).
2137           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2138             Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2139                             : clang::diag::err_drv_unknown_stdin_type);
2140           Ty = types::TY_C;
2141         } else {
2142           // Otherwise lookup by extension.
2143           // Fallback is C if invoked as C preprocessor, C++ if invoked with
2144           // clang-cl /E, or Object otherwise.
2145           // We use a host hook here because Darwin at least has its own
2146           // idea of what .s is.
2147           if (const char *Ext = strrchr(Value, '.'))
2148             Ty = TC.LookupTypeForExtension(Ext + 1);
2149 
2150           if (Ty == types::TY_INVALID) {
2151             if (CCCIsCPP())
2152               Ty = types::TY_C;
2153             else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2154               Ty = types::TY_CXX;
2155             else
2156               Ty = types::TY_Object;
2157           }
2158 
2159           // If the driver is invoked as C++ compiler (like clang++ or c++) it
2160           // should autodetect some input files as C++ for g++ compatibility.
2161           if (CCCIsCXX()) {
2162             types::ID OldTy = Ty;
2163             Ty = types::lookupCXXTypeForCType(Ty);
2164 
2165             if (Ty != OldTy)
2166               Diag(clang::diag::warn_drv_treating_input_as_cxx)
2167                   << getTypeName(OldTy) << getTypeName(Ty);
2168           }
2169 
2170           // If running with -fthinlto-index=, extensions that normally identify
2171           // native object files actually identify LLVM bitcode files.
2172           if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2173               Ty == types::TY_Object)
2174             Ty = types::TY_LLVM_BC;
2175         }
2176 
2177         // -ObjC and -ObjC++ override the default language, but only for "source
2178         // files". We just treat everything that isn't a linker input as a
2179         // source file.
2180         //
2181         // FIXME: Clean this up if we move the phase sequence into the type.
2182         if (Ty != types::TY_Object) {
2183           if (Args.hasArg(options::OPT_ObjC))
2184             Ty = types::TY_ObjC;
2185           else if (Args.hasArg(options::OPT_ObjCXX))
2186             Ty = types::TY_ObjCXX;
2187         }
2188       } else {
2189         assert(InputTypeArg && "InputType set w/o InputTypeArg");
2190         if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2191           // If emulating cl.exe, make sure that /TC and /TP don't affect input
2192           // object files.
2193           const char *Ext = strrchr(Value, '.');
2194           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2195             Ty = types::TY_Object;
2196         }
2197         if (Ty == types::TY_INVALID) {
2198           Ty = InputType;
2199           InputTypeArg->claim();
2200         }
2201       }
2202 
2203       if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2204         Inputs.push_back(std::make_pair(Ty, A));
2205 
2206     } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2207       StringRef Value = A->getValue();
2208       if (DiagnoseInputExistence(Args, Value, types::TY_C,
2209                                  /*TypoCorrect=*/false)) {
2210         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2211         Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2212       }
2213       A->claim();
2214     } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2215       StringRef Value = A->getValue();
2216       if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2217                                  /*TypoCorrect=*/false)) {
2218         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2219         Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2220       }
2221       A->claim();
2222     } else if (A->getOption().hasFlag(options::LinkerInput)) {
2223       // Just treat as object type, we could make a special type for this if
2224       // necessary.
2225       Inputs.push_back(std::make_pair(types::TY_Object, A));
2226 
2227     } else if (A->getOption().matches(options::OPT_x)) {
2228       InputTypeArg = A;
2229       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2230       A->claim();
2231 
2232       // Follow gcc behavior and treat as linker input for invalid -x
2233       // options. Its not clear why we shouldn't just revert to unknown; but
2234       // this isn't very important, we might as well be bug compatible.
2235       if (!InputType) {
2236         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2237         InputType = types::TY_Object;
2238       }
2239     } else if (A->getOption().getID() == options::OPT_U) {
2240       assert(A->getNumValues() == 1 && "The /U option has one value.");
2241       StringRef Val = A->getValue(0);
2242       if (Val.find_first_of("/\\") != StringRef::npos) {
2243         // Warn about e.g. "/Users/me/myfile.c".
2244         Diag(diag::warn_slash_u_filename) << Val;
2245         Diag(diag::note_use_dashdash);
2246       }
2247     }
2248   }
2249   if (CCCIsCPP() && Inputs.empty()) {
2250     // If called as standalone preprocessor, stdin is processed
2251     // if no other input is present.
2252     Arg *A = MakeInputArg(Args, Opts, "-");
2253     Inputs.push_back(std::make_pair(types::TY_C, A));
2254   }
2255 }
2256 
2257 namespace {
2258 /// Provides a convenient interface for different programming models to generate
2259 /// the required device actions.
2260 class OffloadingActionBuilder final {
2261   /// Flag used to trace errors in the builder.
2262   bool IsValid = false;
2263 
2264   /// The compilation that is using this builder.
2265   Compilation &C;
2266 
2267   /// Map between an input argument and the offload kinds used to process it.
2268   std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2269 
2270   /// Builder interface. It doesn't build anything or keep any state.
2271   class DeviceActionBuilder {
2272   public:
2273     typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2274 
2275     enum ActionBuilderReturnCode {
2276       // The builder acted successfully on the current action.
2277       ABRT_Success,
2278       // The builder didn't have to act on the current action.
2279       ABRT_Inactive,
2280       // The builder was successful and requested the host action to not be
2281       // generated.
2282       ABRT_Ignore_Host,
2283     };
2284 
2285   protected:
2286     /// Compilation associated with this builder.
2287     Compilation &C;
2288 
2289     /// Tool chains associated with this builder. The same programming
2290     /// model may have associated one or more tool chains.
2291     SmallVector<const ToolChain *, 2> ToolChains;
2292 
2293     /// The derived arguments associated with this builder.
2294     DerivedArgList &Args;
2295 
2296     /// The inputs associated with this builder.
2297     const Driver::InputList &Inputs;
2298 
2299     /// The associated offload kind.
2300     Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2301 
2302   public:
2303     DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2304                         const Driver::InputList &Inputs,
2305                         Action::OffloadKind AssociatedOffloadKind)
2306         : C(C), Args(Args), Inputs(Inputs),
2307           AssociatedOffloadKind(AssociatedOffloadKind) {}
2308     virtual ~DeviceActionBuilder() {}
2309 
2310     /// Fill up the array \a DA with all the device dependences that should be
2311     /// added to the provided host action \a HostAction. By default it is
2312     /// inactive.
2313     virtual ActionBuilderReturnCode
2314     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2315                          phases::ID CurPhase, phases::ID FinalPhase,
2316                          PhasesTy &Phases) {
2317       return ABRT_Inactive;
2318     }
2319 
2320     /// Update the state to include the provided host action \a HostAction as a
2321     /// dependency of the current device action. By default it is inactive.
2322     virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2323       return ABRT_Inactive;
2324     }
2325 
2326     /// Append top level actions generated by the builder.
2327     virtual void appendTopLevelActions(ActionList &AL) {}
2328 
2329     /// Append linker device actions generated by the builder.
2330     virtual void appendLinkDeviceActions(ActionList &AL) {}
2331 
2332     /// Append linker host action generated by the builder.
2333     virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2334 
2335     /// Append linker actions generated by the builder.
2336     virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2337 
2338     /// Initialize the builder. Return true if any initialization errors are
2339     /// found.
2340     virtual bool initialize() { return false; }
2341 
2342     /// Return true if the builder can use bundling/unbundling.
2343     virtual bool canUseBundlerUnbundler() const { return false; }
2344 
2345     /// Return true if this builder is valid. We have a valid builder if we have
2346     /// associated device tool chains.
2347     bool isValid() { return !ToolChains.empty(); }
2348 
2349     /// Return the associated offload kind.
2350     Action::OffloadKind getAssociatedOffloadKind() {
2351       return AssociatedOffloadKind;
2352     }
2353   };
2354 
2355   /// Base class for CUDA/HIP action builder. It injects device code in
2356   /// the host backend action.
2357   class CudaActionBuilderBase : public DeviceActionBuilder {
2358   protected:
2359     /// Flags to signal if the user requested host-only or device-only
2360     /// compilation.
2361     bool CompileHostOnly = false;
2362     bool CompileDeviceOnly = false;
2363     bool EmitLLVM = false;
2364     bool EmitAsm = false;
2365 
2366     /// List of GPU architectures to use in this compilation.
2367     SmallVector<CudaArch, 4> GpuArchList;
2368 
2369     /// The CUDA actions for the current input.
2370     ActionList CudaDeviceActions;
2371 
2372     /// The CUDA fat binary if it was generated for the current input.
2373     Action *CudaFatBinary = nullptr;
2374 
2375     /// Flag that is set to true if this builder acted on the current input.
2376     bool IsActive = false;
2377 
2378     /// Flag for -fgpu-rdc.
2379     bool Relocatable = false;
2380 
2381     /// Default GPU architecture if there's no one specified.
2382     CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2383 
2384   public:
2385     CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2386                           const Driver::InputList &Inputs,
2387                           Action::OffloadKind OFKind)
2388         : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2389 
2390     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2391       // While generating code for CUDA, we only depend on the host input action
2392       // to trigger the creation of all the CUDA device actions.
2393 
2394       // If we are dealing with an input action, replicate it for each GPU
2395       // architecture. If we are in host-only mode we return 'success' so that
2396       // the host uses the CUDA offload kind.
2397       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2398         assert(!GpuArchList.empty() &&
2399                "We should have at least one GPU architecture.");
2400 
2401         // If the host input is not CUDA or HIP, we don't need to bother about
2402         // this input.
2403         if (IA->getType() != types::TY_CUDA &&
2404             IA->getType() != types::TY_HIP) {
2405           // The builder will ignore this input.
2406           IsActive = false;
2407           return ABRT_Inactive;
2408         }
2409 
2410         // Set the flag to true, so that the builder acts on the current input.
2411         IsActive = true;
2412 
2413         if (CompileHostOnly)
2414           return ABRT_Success;
2415 
2416         // Replicate inputs for each GPU architecture.
2417         auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2418                                                  : types::TY_CUDA_DEVICE;
2419         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2420           CudaDeviceActions.push_back(
2421               C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2422         }
2423 
2424         return ABRT_Success;
2425       }
2426 
2427       // If this is an unbundling action use it as is for each CUDA toolchain.
2428       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2429 
2430         // If -fgpu-rdc is disabled, should not unbundle since there is no
2431         // device code to link.
2432         if (!Relocatable)
2433           return ABRT_Inactive;
2434 
2435         CudaDeviceActions.clear();
2436         auto *IA = cast<InputAction>(UA->getInputs().back());
2437         std::string FileName = IA->getInputArg().getAsString(Args);
2438         // Check if the type of the file is the same as the action. Do not
2439         // unbundle it if it is not. Do not unbundle .so files, for example,
2440         // which are not object files.
2441         if (IA->getType() == types::TY_Object &&
2442             (!llvm::sys::path::has_extension(FileName) ||
2443              types::lookupTypeForExtension(
2444                  llvm::sys::path::extension(FileName).drop_front()) !=
2445                  types::TY_Object))
2446           return ABRT_Inactive;
2447 
2448         for (auto Arch : GpuArchList) {
2449           CudaDeviceActions.push_back(UA);
2450           UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2451                                           AssociatedOffloadKind);
2452         }
2453         return ABRT_Success;
2454       }
2455 
2456       return IsActive ? ABRT_Success : ABRT_Inactive;
2457     }
2458 
2459     void appendTopLevelActions(ActionList &AL) override {
2460       // Utility to append actions to the top level list.
2461       auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2462         OffloadAction::DeviceDependences Dep;
2463         Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2464                 AssociatedOffloadKind);
2465         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2466       };
2467 
2468       // If we have a fat binary, add it to the list.
2469       if (CudaFatBinary) {
2470         AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2471         CudaDeviceActions.clear();
2472         CudaFatBinary = nullptr;
2473         return;
2474       }
2475 
2476       if (CudaDeviceActions.empty())
2477         return;
2478 
2479       // If we have CUDA actions at this point, that's because we have a have
2480       // partial compilation, so we should have an action for each GPU
2481       // architecture.
2482       assert(CudaDeviceActions.size() == GpuArchList.size() &&
2483              "Expecting one action per GPU architecture.");
2484       assert(ToolChains.size() == 1 &&
2485              "Expecting to have a sing CUDA toolchain.");
2486       for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2487         AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2488 
2489       CudaDeviceActions.clear();
2490     }
2491 
2492     bool initialize() override {
2493       assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2494              AssociatedOffloadKind == Action::OFK_HIP);
2495 
2496       // We don't need to support CUDA.
2497       if (AssociatedOffloadKind == Action::OFK_Cuda &&
2498           !C.hasOffloadToolChain<Action::OFK_Cuda>())
2499         return false;
2500 
2501       // We don't need to support HIP.
2502       if (AssociatedOffloadKind == Action::OFK_HIP &&
2503           !C.hasOffloadToolChain<Action::OFK_HIP>())
2504         return false;
2505 
2506       Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2507           options::OPT_fno_gpu_rdc, /*Default=*/false);
2508 
2509       const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2510       assert(HostTC && "No toolchain for host compilation.");
2511       if (HostTC->getTriple().isNVPTX() ||
2512           HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2513         // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2514         // an error and abort pipeline construction early so we don't trip
2515         // asserts that assume device-side compilation.
2516         C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2517             << HostTC->getTriple().getArchName();
2518         return true;
2519       }
2520 
2521       ToolChains.push_back(
2522           AssociatedOffloadKind == Action::OFK_Cuda
2523               ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2524               : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2525 
2526       Arg *PartialCompilationArg = Args.getLastArg(
2527           options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2528           options::OPT_cuda_compile_host_device);
2529       CompileHostOnly = PartialCompilationArg &&
2530                         PartialCompilationArg->getOption().matches(
2531                             options::OPT_cuda_host_only);
2532       CompileDeviceOnly = PartialCompilationArg &&
2533                           PartialCompilationArg->getOption().matches(
2534                               options::OPT_cuda_device_only);
2535       EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
2536       EmitAsm = Args.getLastArg(options::OPT_S);
2537 
2538       // Collect all cuda_gpu_arch parameters, removing duplicates.
2539       std::set<CudaArch> GpuArchs;
2540       bool Error = false;
2541       for (Arg *A : Args) {
2542         if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
2543               A->getOption().matches(options::OPT_no_offload_arch_EQ)))
2544           continue;
2545         A->claim();
2546 
2547         const StringRef ArchStr = A->getValue();
2548         if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
2549             ArchStr == "all") {
2550           GpuArchs.clear();
2551           continue;
2552         }
2553         CudaArch Arch = StringToCudaArch(ArchStr);
2554         if (Arch == CudaArch::UNKNOWN) {
2555           C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2556           Error = true;
2557         } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
2558           GpuArchs.insert(Arch);
2559         else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
2560           GpuArchs.erase(Arch);
2561         else
2562           llvm_unreachable("Unexpected option.");
2563       }
2564 
2565       // Collect list of GPUs remaining in the set.
2566       for (CudaArch Arch : GpuArchs)
2567         GpuArchList.push_back(Arch);
2568 
2569       // Default to sm_20 which is the lowest common denominator for
2570       // supported GPUs.  sm_20 code should work correctly, if
2571       // suboptimally, on all newer GPUs.
2572       if (GpuArchList.empty())
2573         GpuArchList.push_back(DefaultCudaArch);
2574 
2575       return Error;
2576     }
2577   };
2578 
2579   /// \brief CUDA action builder. It injects device code in the host backend
2580   /// action.
2581   class CudaActionBuilder final : public CudaActionBuilderBase {
2582   public:
2583     CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2584                       const Driver::InputList &Inputs)
2585         : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
2586       DefaultCudaArch = CudaArch::SM_20;
2587     }
2588 
2589     ActionBuilderReturnCode
2590     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2591                          phases::ID CurPhase, phases::ID FinalPhase,
2592                          PhasesTy &Phases) override {
2593       if (!IsActive)
2594         return ABRT_Inactive;
2595 
2596       // If we don't have more CUDA actions, we don't have any dependences to
2597       // create for the host.
2598       if (CudaDeviceActions.empty())
2599         return ABRT_Success;
2600 
2601       assert(CudaDeviceActions.size() == GpuArchList.size() &&
2602              "Expecting one action per GPU architecture.");
2603       assert(!CompileHostOnly &&
2604              "Not expecting CUDA actions in host-only compilation.");
2605 
2606       // If we are generating code for the device or we are in a backend phase,
2607       // we attempt to generate the fat binary. We compile each arch to ptx and
2608       // assemble to cubin, then feed the cubin *and* the ptx into a device
2609       // "link" action, which uses fatbinary to combine these cubins into one
2610       // fatbin.  The fatbin is then an input to the host action if not in
2611       // device-only mode.
2612       if (CompileDeviceOnly || CurPhase == phases::Backend) {
2613         ActionList DeviceActions;
2614         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2615           // Produce the device action from the current phase up to the assemble
2616           // phase.
2617           for (auto Ph : Phases) {
2618             // Skip the phases that were already dealt with.
2619             if (Ph < CurPhase)
2620               continue;
2621             // We have to be consistent with the host final phase.
2622             if (Ph > FinalPhase)
2623               break;
2624 
2625             CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2626                 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
2627 
2628             if (Ph == phases::Assemble)
2629               break;
2630           }
2631 
2632           // If we didn't reach the assemble phase, we can't generate the fat
2633           // binary. We don't need to generate the fat binary if we are not in
2634           // device-only mode.
2635           if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2636               CompileDeviceOnly)
2637             continue;
2638 
2639           Action *AssembleAction = CudaDeviceActions[I];
2640           assert(AssembleAction->getType() == types::TY_Object);
2641           assert(AssembleAction->getInputs().size() == 1);
2642 
2643           Action *BackendAction = AssembleAction->getInputs()[0];
2644           assert(BackendAction->getType() == types::TY_PP_Asm);
2645 
2646           for (auto &A : {AssembleAction, BackendAction}) {
2647             OffloadAction::DeviceDependences DDep;
2648             DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2649                      Action::OFK_Cuda);
2650             DeviceActions.push_back(
2651                 C.MakeAction<OffloadAction>(DDep, A->getType()));
2652           }
2653         }
2654 
2655         // We generate the fat binary if we have device input actions.
2656         if (!DeviceActions.empty()) {
2657           CudaFatBinary =
2658               C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2659 
2660           if (!CompileDeviceOnly) {
2661             DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2662                    Action::OFK_Cuda);
2663             // Clear the fat binary, it is already a dependence to an host
2664             // action.
2665             CudaFatBinary = nullptr;
2666           }
2667 
2668           // Remove the CUDA actions as they are already connected to an host
2669           // action or fat binary.
2670           CudaDeviceActions.clear();
2671         }
2672 
2673         // We avoid creating host action in device-only mode.
2674         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2675       } else if (CurPhase > phases::Backend) {
2676         // If we are past the backend phase and still have a device action, we
2677         // don't have to do anything as this action is already a device
2678         // top-level action.
2679         return ABRT_Success;
2680       }
2681 
2682       assert(CurPhase < phases::Backend && "Generating single CUDA "
2683                                            "instructions should only occur "
2684                                            "before the backend phase!");
2685 
2686       // By default, we produce an action for each device arch.
2687       for (Action *&A : CudaDeviceActions)
2688         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2689 
2690       return ABRT_Success;
2691     }
2692   };
2693   /// \brief HIP action builder. It injects device code in the host backend
2694   /// action.
2695   class HIPActionBuilder final : public CudaActionBuilderBase {
2696     /// The linker inputs obtained for each device arch.
2697     SmallVector<ActionList, 8> DeviceLinkerInputs;
2698 
2699   public:
2700     HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2701                      const Driver::InputList &Inputs)
2702         : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
2703       DefaultCudaArch = CudaArch::GFX803;
2704     }
2705 
2706     bool canUseBundlerUnbundler() const override { return true; }
2707 
2708     ActionBuilderReturnCode
2709     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2710                          phases::ID CurPhase, phases::ID FinalPhase,
2711                          PhasesTy &Phases) override {
2712       // amdgcn does not support linking of object files, therefore we skip
2713       // backend and assemble phases to output LLVM IR. Except for generating
2714       // non-relocatable device coee, where we generate fat binary for device
2715       // code and pass to host in Backend phase.
2716       if (CudaDeviceActions.empty())
2717         return ABRT_Success;
2718 
2719       assert(((CurPhase == phases::Link && Relocatable) ||
2720               CudaDeviceActions.size() == GpuArchList.size()) &&
2721              "Expecting one action per GPU architecture.");
2722       assert(!CompileHostOnly &&
2723              "Not expecting CUDA actions in host-only compilation.");
2724 
2725       if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
2726           !EmitAsm) {
2727         // If we are in backend phase, we attempt to generate the fat binary.
2728         // We compile each arch to IR and use a link action to generate code
2729         // object containing ISA. Then we use a special "link" action to create
2730         // a fat binary containing all the code objects for different GPU's.
2731         // The fat binary is then an input to the host action.
2732         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2733           auto BackendAction = C.getDriver().ConstructPhaseAction(
2734               C, Args, phases::Backend, CudaDeviceActions[I],
2735               AssociatedOffloadKind);
2736           auto AssembleAction = C.getDriver().ConstructPhaseAction(
2737               C, Args, phases::Assemble, BackendAction, AssociatedOffloadKind);
2738           // Create a link action to link device IR with device library
2739           // and generate ISA.
2740           ActionList AL;
2741           AL.push_back(AssembleAction);
2742           CudaDeviceActions[I] =
2743               C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2744 
2745           // OffloadingActionBuilder propagates device arch until an offload
2746           // action. Since the next action for creating fatbin does
2747           // not have device arch, whereas the above link action and its input
2748           // have device arch, an offload action is needed to stop the null
2749           // device arch of the next action being propagated to the above link
2750           // action.
2751           OffloadAction::DeviceDependences DDep;
2752           DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2753                    CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2754           CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2755               DDep, CudaDeviceActions[I]->getType());
2756         }
2757         // Create HIP fat binary with a special "link" action.
2758         CudaFatBinary =
2759             C.MakeAction<LinkJobAction>(CudaDeviceActions,
2760                 types::TY_HIP_FATBIN);
2761 
2762         if (!CompileDeviceOnly) {
2763           DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2764                  AssociatedOffloadKind);
2765           // Clear the fat binary, it is already a dependence to an host
2766           // action.
2767           CudaFatBinary = nullptr;
2768         }
2769 
2770         // Remove the CUDA actions as they are already connected to an host
2771         // action or fat binary.
2772         CudaDeviceActions.clear();
2773 
2774         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2775       } else if (CurPhase == phases::Link) {
2776         // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2777         // This happens to each device action originated from each input file.
2778         // Later on, device actions in DeviceLinkerInputs are used to create
2779         // device link actions in appendLinkDependences and the created device
2780         // link actions are passed to the offload action as device dependence.
2781         DeviceLinkerInputs.resize(CudaDeviceActions.size());
2782         auto LI = DeviceLinkerInputs.begin();
2783         for (auto *A : CudaDeviceActions) {
2784           LI->push_back(A);
2785           ++LI;
2786         }
2787 
2788         // We will pass the device action as a host dependence, so we don't
2789         // need to do anything else with them.
2790         CudaDeviceActions.clear();
2791         return ABRT_Success;
2792       }
2793 
2794       // By default, we produce an action for each device arch.
2795       for (Action *&A : CudaDeviceActions)
2796         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2797                                                AssociatedOffloadKind);
2798 
2799       return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
2800                                                            : ABRT_Success;
2801     }
2802 
2803     void appendLinkDeviceActions(ActionList &AL) override {
2804       if (DeviceLinkerInputs.size() == 0)
2805         return;
2806 
2807       assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
2808              "Linker inputs and GPU arch list sizes do not match.");
2809 
2810       // Append a new link action for each device.
2811       unsigned I = 0;
2812       for (auto &LI : DeviceLinkerInputs) {
2813         // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
2814         auto *DeviceLinkAction =
2815             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2816         // Linking all inputs for the current GPU arch.
2817         // LI contains all the inputs for the linker.
2818         OffloadAction::DeviceDependences DeviceLinkDeps;
2819         DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
2820             CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2821         AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
2822             DeviceLinkAction->getType()));
2823         ++I;
2824       }
2825       DeviceLinkerInputs.clear();
2826 
2827       // Create a host object from all the device images by embedding them
2828       // in a fat binary.
2829       OffloadAction::DeviceDependences DDeps;
2830       auto *TopDeviceLinkAction =
2831           C.MakeAction<LinkJobAction>(AL, types::TY_Object);
2832       DDeps.add(*TopDeviceLinkAction, *ToolChains[0],
2833           nullptr, AssociatedOffloadKind);
2834 
2835       // Offload the host object to the host linker.
2836       AL.push_back(C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
2837     }
2838 
2839     Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
2840 
2841     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
2842   };
2843 
2844   /// OpenMP action builder. The host bitcode is passed to the device frontend
2845   /// and all the device linked images are passed to the host link phase.
2846   class OpenMPActionBuilder final : public DeviceActionBuilder {
2847     /// The OpenMP actions for the current input.
2848     ActionList OpenMPDeviceActions;
2849 
2850     /// The linker inputs obtained for each toolchain.
2851     SmallVector<ActionList, 8> DeviceLinkerInputs;
2852 
2853   public:
2854     OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2855                         const Driver::InputList &Inputs)
2856         : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2857 
2858     ActionBuilderReturnCode
2859     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2860                          phases::ID CurPhase, phases::ID FinalPhase,
2861                          PhasesTy &Phases) override {
2862       if (OpenMPDeviceActions.empty())
2863         return ABRT_Inactive;
2864 
2865       // We should always have an action for each input.
2866       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2867              "Number of OpenMP actions and toolchains do not match.");
2868 
2869       // The host only depends on device action in the linking phase, when all
2870       // the device images have to be embedded in the host image.
2871       if (CurPhase == phases::Link) {
2872         assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2873                "Toolchains and linker inputs sizes do not match.");
2874         auto LI = DeviceLinkerInputs.begin();
2875         for (auto *A : OpenMPDeviceActions) {
2876           LI->push_back(A);
2877           ++LI;
2878         }
2879 
2880         // We passed the device action as a host dependence, so we don't need to
2881         // do anything else with them.
2882         OpenMPDeviceActions.clear();
2883         return ABRT_Success;
2884       }
2885 
2886       // By default, we produce an action for each device arch.
2887       for (Action *&A : OpenMPDeviceActions)
2888         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2889 
2890       return ABRT_Success;
2891     }
2892 
2893     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2894 
2895       // If this is an input action replicate it for each OpenMP toolchain.
2896       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2897         OpenMPDeviceActions.clear();
2898         for (unsigned I = 0; I < ToolChains.size(); ++I)
2899           OpenMPDeviceActions.push_back(
2900               C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2901         return ABRT_Success;
2902       }
2903 
2904       // If this is an unbundling action use it as is for each OpenMP toolchain.
2905       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2906         OpenMPDeviceActions.clear();
2907         auto *IA = cast<InputAction>(UA->getInputs().back());
2908         std::string FileName = IA->getInputArg().getAsString(Args);
2909         // Check if the type of the file is the same as the action. Do not
2910         // unbundle it if it is not. Do not unbundle .so files, for example,
2911         // which are not object files.
2912         if (IA->getType() == types::TY_Object &&
2913             (!llvm::sys::path::has_extension(FileName) ||
2914              types::lookupTypeForExtension(
2915                  llvm::sys::path::extension(FileName).drop_front()) !=
2916                  types::TY_Object))
2917           return ABRT_Inactive;
2918         for (unsigned I = 0; I < ToolChains.size(); ++I) {
2919           OpenMPDeviceActions.push_back(UA);
2920           UA->registerDependentActionInfo(
2921               ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2922         }
2923         return ABRT_Success;
2924       }
2925 
2926       // When generating code for OpenMP we use the host compile phase result as
2927       // a dependence to the device compile phase so that it can learn what
2928       // declarations should be emitted. However, this is not the only use for
2929       // the host action, so we prevent it from being collapsed.
2930       if (isa<CompileJobAction>(HostAction)) {
2931         HostAction->setCannotBeCollapsedWithNextDependentAction();
2932         assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2933                "Toolchains and device action sizes do not match.");
2934         OffloadAction::HostDependence HDep(
2935             *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2936             /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2937         auto TC = ToolChains.begin();
2938         for (Action *&A : OpenMPDeviceActions) {
2939           assert(isa<CompileJobAction>(A));
2940           OffloadAction::DeviceDependences DDep;
2941           DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2942           A = C.MakeAction<OffloadAction>(HDep, DDep);
2943           ++TC;
2944         }
2945       }
2946       return ABRT_Success;
2947     }
2948 
2949     void appendTopLevelActions(ActionList &AL) override {
2950       if (OpenMPDeviceActions.empty())
2951         return;
2952 
2953       // We should always have an action for each input.
2954       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2955              "Number of OpenMP actions and toolchains do not match.");
2956 
2957       // Append all device actions followed by the proper offload action.
2958       auto TI = ToolChains.begin();
2959       for (auto *A : OpenMPDeviceActions) {
2960         OffloadAction::DeviceDependences Dep;
2961         Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2962         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2963         ++TI;
2964       }
2965       // We no longer need the action stored in this builder.
2966       OpenMPDeviceActions.clear();
2967     }
2968 
2969     void appendLinkDeviceActions(ActionList &AL) override {
2970       assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2971              "Toolchains and linker inputs sizes do not match.");
2972 
2973       // Append a new link action for each device.
2974       auto TC = ToolChains.begin();
2975       for (auto &LI : DeviceLinkerInputs) {
2976         auto *DeviceLinkAction =
2977             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2978         OffloadAction::DeviceDependences DeviceLinkDeps;
2979         DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2980 		        Action::OFK_OpenMP);
2981         AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
2982             DeviceLinkAction->getType()));
2983         ++TC;
2984       }
2985       DeviceLinkerInputs.clear();
2986     }
2987 
2988     Action* appendLinkHostActions(ActionList &AL) override {
2989       // Create wrapper bitcode from the result of device link actions and compile
2990       // it to an object which will be added to the host link command.
2991       auto *BC = C.MakeAction<OffloadWrapperJobAction>(AL, types::TY_LLVM_BC);
2992       auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm);
2993       return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object);
2994     }
2995 
2996     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
2997 
2998     bool initialize() override {
2999       // Get the OpenMP toolchains. If we don't get any, the action builder will
3000       // know there is nothing to do related to OpenMP offloading.
3001       auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
3002       for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
3003            ++TI)
3004         ToolChains.push_back(TI->second);
3005 
3006       DeviceLinkerInputs.resize(ToolChains.size());
3007       return false;
3008     }
3009 
3010     bool canUseBundlerUnbundler() const override {
3011       // OpenMP should use bundled files whenever possible.
3012       return true;
3013     }
3014   };
3015 
3016   ///
3017   /// TODO: Add the implementation for other specialized builders here.
3018   ///
3019 
3020   /// Specialized builders being used by this offloading action builder.
3021   SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3022 
3023   /// Flag set to true if all valid builders allow file bundling/unbundling.
3024   bool CanUseBundler;
3025 
3026 public:
3027   OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3028                           const Driver::InputList &Inputs)
3029       : C(C) {
3030     // Create a specialized builder for each device toolchain.
3031 
3032     IsValid = true;
3033 
3034     // Create a specialized builder for CUDA.
3035     SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3036 
3037     // Create a specialized builder for HIP.
3038     SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3039 
3040     // Create a specialized builder for OpenMP.
3041     SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
3042 
3043     //
3044     // TODO: Build other specialized builders here.
3045     //
3046 
3047     // Initialize all the builders, keeping track of errors. If all valid
3048     // builders agree that we can use bundling, set the flag to true.
3049     unsigned ValidBuilders = 0u;
3050     unsigned ValidBuildersSupportingBundling = 0u;
3051     for (auto *SB : SpecializedBuilders) {
3052       IsValid = IsValid && !SB->initialize();
3053 
3054       // Update the counters if the builder is valid.
3055       if (SB->isValid()) {
3056         ++ValidBuilders;
3057         if (SB->canUseBundlerUnbundler())
3058           ++ValidBuildersSupportingBundling;
3059       }
3060     }
3061     CanUseBundler =
3062         ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3063   }
3064 
3065   ~OffloadingActionBuilder() {
3066     for (auto *SB : SpecializedBuilders)
3067       delete SB;
3068   }
3069 
3070   /// Generate an action that adds device dependences (if any) to a host action.
3071   /// If no device dependence actions exist, just return the host action \a
3072   /// HostAction. If an error is found or if no builder requires the host action
3073   /// to be generated, return nullptr.
3074   Action *
3075   addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3076                                    phases::ID CurPhase, phases::ID FinalPhase,
3077                                    DeviceActionBuilder::PhasesTy &Phases) {
3078     if (!IsValid)
3079       return nullptr;
3080 
3081     if (SpecializedBuilders.empty())
3082       return HostAction;
3083 
3084     assert(HostAction && "Invalid host action!");
3085 
3086     OffloadAction::DeviceDependences DDeps;
3087     // Check if all the programming models agree we should not emit the host
3088     // action. Also, keep track of the offloading kinds employed.
3089     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3090     unsigned InactiveBuilders = 0u;
3091     unsigned IgnoringBuilders = 0u;
3092     for (auto *SB : SpecializedBuilders) {
3093       if (!SB->isValid()) {
3094         ++InactiveBuilders;
3095         continue;
3096       }
3097 
3098       auto RetCode =
3099           SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3100 
3101       // If the builder explicitly says the host action should be ignored,
3102       // we need to increment the variable that tracks the builders that request
3103       // the host object to be ignored.
3104       if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3105         ++IgnoringBuilders;
3106 
3107       // Unless the builder was inactive for this action, we have to record the
3108       // offload kind because the host will have to use it.
3109       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3110         OffloadKind |= SB->getAssociatedOffloadKind();
3111     }
3112 
3113     // If all builders agree that the host object should be ignored, just return
3114     // nullptr.
3115     if (IgnoringBuilders &&
3116         SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3117       return nullptr;
3118 
3119     if (DDeps.getActions().empty())
3120       return HostAction;
3121 
3122     // We have dependences we need to bundle together. We use an offload action
3123     // for that.
3124     OffloadAction::HostDependence HDep(
3125         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3126         /*BoundArch=*/nullptr, DDeps);
3127     return C.MakeAction<OffloadAction>(HDep, DDeps);
3128   }
3129 
3130   /// Generate an action that adds a host dependence to a device action. The
3131   /// results will be kept in this action builder. Return true if an error was
3132   /// found.
3133   bool addHostDependenceToDeviceActions(Action *&HostAction,
3134                                         const Arg *InputArg) {
3135     if (!IsValid)
3136       return true;
3137 
3138     // If we are supporting bundling/unbundling and the current action is an
3139     // input action of non-source file, we replace the host action by the
3140     // unbundling action. The bundler tool has the logic to detect if an input
3141     // is a bundle or not and if the input is not a bundle it assumes it is a
3142     // host file. Therefore it is safe to create an unbundling action even if
3143     // the input is not a bundle.
3144     if (CanUseBundler && isa<InputAction>(HostAction) &&
3145         InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3146         !types::isSrcFile(HostAction->getType())) {
3147       auto UnbundlingHostAction =
3148           C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3149       UnbundlingHostAction->registerDependentActionInfo(
3150           C.getSingleOffloadToolChain<Action::OFK_Host>(),
3151           /*BoundArch=*/StringRef(), Action::OFK_Host);
3152       HostAction = UnbundlingHostAction;
3153     }
3154 
3155     assert(HostAction && "Invalid host action!");
3156 
3157     // Register the offload kinds that are used.
3158     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3159     for (auto *SB : SpecializedBuilders) {
3160       if (!SB->isValid())
3161         continue;
3162 
3163       auto RetCode = SB->addDeviceDepences(HostAction);
3164 
3165       // Host dependences for device actions are not compatible with that same
3166       // action being ignored.
3167       assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3168              "Host dependence not expected to be ignored.!");
3169 
3170       // Unless the builder was inactive for this action, we have to record the
3171       // offload kind because the host will have to use it.
3172       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3173         OffloadKind |= SB->getAssociatedOffloadKind();
3174     }
3175 
3176     // Do not use unbundler if the Host does not depend on device action.
3177     if (OffloadKind == Action::OFK_None && CanUseBundler)
3178       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3179         HostAction = UA->getInputs().back();
3180 
3181     return false;
3182   }
3183 
3184   /// Add the offloading top level actions to the provided action list. This
3185   /// function can replace the host action by a bundling action if the
3186   /// programming models allow it.
3187   bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3188                              const Arg *InputArg) {
3189     // Get the device actions to be appended.
3190     ActionList OffloadAL;
3191     for (auto *SB : SpecializedBuilders) {
3192       if (!SB->isValid())
3193         continue;
3194       SB->appendTopLevelActions(OffloadAL);
3195     }
3196 
3197     // If we can use the bundler, replace the host action by the bundling one in
3198     // the resulting list. Otherwise, just append the device actions. For
3199     // device only compilation, HostAction is a null pointer, therefore only do
3200     // this when HostAction is not a null pointer.
3201     if (CanUseBundler && HostAction &&
3202         HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3203       // Add the host action to the list in order to create the bundling action.
3204       OffloadAL.push_back(HostAction);
3205 
3206       // We expect that the host action was just appended to the action list
3207       // before this method was called.
3208       assert(HostAction == AL.back() && "Host action not in the list??");
3209       HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3210       AL.back() = HostAction;
3211     } else
3212       AL.append(OffloadAL.begin(), OffloadAL.end());
3213 
3214     // Propagate to the current host action (if any) the offload information
3215     // associated with the current input.
3216     if (HostAction)
3217       HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3218                                            /*BoundArch=*/nullptr);
3219     return false;
3220   }
3221 
3222   Action* makeHostLinkAction() {
3223     // Build a list of device linking actions.
3224     ActionList DeviceAL;
3225     for (DeviceActionBuilder *SB : SpecializedBuilders) {
3226       if (!SB->isValid())
3227         continue;
3228       SB->appendLinkDeviceActions(DeviceAL);
3229     }
3230 
3231     if (DeviceAL.empty())
3232       return nullptr;
3233 
3234     // Let builders add host linking actions.
3235     Action* HA;
3236     for (DeviceActionBuilder *SB : SpecializedBuilders) {
3237       if (!SB->isValid())
3238         continue;
3239       HA = SB->appendLinkHostActions(DeviceAL);
3240     }
3241     return HA;
3242   }
3243 
3244   /// Processes the host linker action. This currently consists of replacing it
3245   /// with an offload action if there are device link objects and propagate to
3246   /// the host action all the offload kinds used in the current compilation. The
3247   /// resulting action is returned.
3248   Action *processHostLinkAction(Action *HostAction) {
3249     // Add all the dependences from the device linking actions.
3250     OffloadAction::DeviceDependences DDeps;
3251     for (auto *SB : SpecializedBuilders) {
3252       if (!SB->isValid())
3253         continue;
3254 
3255       SB->appendLinkDependences(DDeps);
3256     }
3257 
3258     // Calculate all the offload kinds used in the current compilation.
3259     unsigned ActiveOffloadKinds = 0u;
3260     for (auto &I : InputArgToOffloadKindMap)
3261       ActiveOffloadKinds |= I.second;
3262 
3263     // If we don't have device dependencies, we don't have to create an offload
3264     // action.
3265     if (DDeps.getActions().empty()) {
3266       // Propagate all the active kinds to host action. Given that it is a link
3267       // action it is assumed to depend on all actions generated so far.
3268       HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3269                                            /*BoundArch=*/nullptr);
3270       return HostAction;
3271     }
3272 
3273     // Create the offload action with all dependences. When an offload action
3274     // is created the kinds are propagated to the host action, so we don't have
3275     // to do that explicitly here.
3276     OffloadAction::HostDependence HDep(
3277         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3278         /*BoundArch*/ nullptr, ActiveOffloadKinds);
3279     return C.MakeAction<OffloadAction>(HDep, DDeps);
3280   }
3281 };
3282 } // anonymous namespace.
3283 
3284 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3285                              const InputList &Inputs,
3286                              ActionList &Actions) const {
3287 
3288   // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3289   Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3290   Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3291   if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3292     Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3293     Args.eraseArg(options::OPT__SLASH_Yc);
3294     Args.eraseArg(options::OPT__SLASH_Yu);
3295     YcArg = YuArg = nullptr;
3296   }
3297   if (YcArg && Inputs.size() > 1) {
3298     Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3299     Args.eraseArg(options::OPT__SLASH_Yc);
3300     YcArg = nullptr;
3301   }
3302 
3303   Arg *FinalPhaseArg;
3304   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3305 
3306   if (FinalPhase == phases::Link) {
3307     if (Args.hasArg(options::OPT_emit_llvm))
3308       Diag(clang::diag::err_drv_emit_llvm_link);
3309     if (IsCLMode() && LTOMode != LTOK_None &&
3310         !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3311       Diag(clang::diag::err_drv_lto_without_lld);
3312   }
3313 
3314   if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3315     // If only preprocessing or /Y- is used, all pch handling is disabled.
3316     // Rather than check for it everywhere, just remove clang-cl pch-related
3317     // flags here.
3318     Args.eraseArg(options::OPT__SLASH_Fp);
3319     Args.eraseArg(options::OPT__SLASH_Yc);
3320     Args.eraseArg(options::OPT__SLASH_Yu);
3321     YcArg = YuArg = nullptr;
3322   }
3323 
3324   unsigned LastPLSize = 0;
3325   for (auto &I : Inputs) {
3326     types::ID InputType = I.first;
3327     const Arg *InputArg = I.second;
3328 
3329     auto PL = types::getCompilationPhases(InputType);
3330     LastPLSize = PL.size();
3331 
3332     // If the first step comes after the final phase we are doing as part of
3333     // this compilation, warn the user about it.
3334     phases::ID InitialPhase = PL[0];
3335     if (InitialPhase > FinalPhase) {
3336       if (InputArg->isClaimed())
3337         continue;
3338 
3339       // Claim here to avoid the more general unused warning.
3340       InputArg->claim();
3341 
3342       // Suppress all unused style warnings with -Qunused-arguments
3343       if (Args.hasArg(options::OPT_Qunused_arguments))
3344         continue;
3345 
3346       // Special case when final phase determined by binary name, rather than
3347       // by a command-line argument with a corresponding Arg.
3348       if (CCCIsCPP())
3349         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3350             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3351       // Special case '-E' warning on a previously preprocessed file to make
3352       // more sense.
3353       else if (InitialPhase == phases::Compile &&
3354                (Args.getLastArg(options::OPT__SLASH_EP,
3355                                 options::OPT__SLASH_P) ||
3356                 Args.getLastArg(options::OPT_E) ||
3357                 Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3358                getPreprocessedType(InputType) == types::TY_INVALID)
3359         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3360             << InputArg->getAsString(Args) << !!FinalPhaseArg
3361             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3362       else
3363         Diag(clang::diag::warn_drv_input_file_unused)
3364             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3365             << !!FinalPhaseArg
3366             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3367       continue;
3368     }
3369 
3370     if (YcArg) {
3371       // Add a separate precompile phase for the compile phase.
3372       if (FinalPhase >= phases::Compile) {
3373         const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3374         // Build the pipeline for the pch file.
3375         Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3376         for (phases::ID Phase : types::getCompilationPhases(HeaderType))
3377           ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3378         assert(ClangClPch);
3379         Actions.push_back(ClangClPch);
3380         // The driver currently exits after the first failed command.  This
3381         // relies on that behavior, to make sure if the pch generation fails,
3382         // the main compilation won't run.
3383         // FIXME: If the main compilation fails, the PCH generation should
3384         // probably not be considered successful either.
3385       }
3386     }
3387   }
3388 
3389   // If we are linking, claim any options which are obviously only used for
3390   // compilation.
3391   // FIXME: Understand why the last Phase List length is used here.
3392   if (FinalPhase == phases::Link && LastPLSize == 1) {
3393     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3394     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3395   }
3396 }
3397 
3398 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3399                           const InputList &Inputs, ActionList &Actions) const {
3400   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3401 
3402   if (!SuppressMissingInputWarning && Inputs.empty()) {
3403     Diag(clang::diag::err_drv_no_input_files);
3404     return;
3405   }
3406 
3407   // Reject -Z* at the top level, these options should never have been exposed
3408   // by gcc.
3409   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
3410     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
3411 
3412   // Diagnose misuse of /Fo.
3413   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3414     StringRef V = A->getValue();
3415     if (Inputs.size() > 1 && !V.empty() &&
3416         !llvm::sys::path::is_separator(V.back())) {
3417       // Check whether /Fo tries to name an output file for multiple inputs.
3418       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3419           << A->getSpelling() << V;
3420       Args.eraseArg(options::OPT__SLASH_Fo);
3421     }
3422   }
3423 
3424   // Diagnose misuse of /Fa.
3425   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3426     StringRef V = A->getValue();
3427     if (Inputs.size() > 1 && !V.empty() &&
3428         !llvm::sys::path::is_separator(V.back())) {
3429       // Check whether /Fa tries to name an asm file for multiple inputs.
3430       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3431           << A->getSpelling() << V;
3432       Args.eraseArg(options::OPT__SLASH_Fa);
3433     }
3434   }
3435 
3436   // Diagnose misuse of /o.
3437   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3438     if (A->getValue()[0] == '\0') {
3439       // It has to have a value.
3440       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3441       Args.eraseArg(options::OPT__SLASH_o);
3442     }
3443   }
3444 
3445   handleArguments(C, Args, Inputs, Actions);
3446 
3447   // Builder to be used to build offloading actions.
3448   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3449 
3450   // Construct the actions to perform.
3451   HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3452   ActionList LinkerInputs;
3453   ActionList MergerInputs;
3454 
3455   for (auto &I : Inputs) {
3456     types::ID InputType = I.first;
3457     const Arg *InputArg = I.second;
3458 
3459     auto PL = types::getCompilationPhases(*this, Args, InputType);
3460     if (PL.empty())
3461       continue;
3462 
3463     auto FullPL = types::getCompilationPhases(InputType);
3464 
3465     // Build the pipeline for this file.
3466     Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3467 
3468     // Use the current host action in any of the offloading actions, if
3469     // required.
3470     if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3471       break;
3472 
3473     for (phases::ID Phase : PL) {
3474 
3475       // Add any offload action the host action depends on.
3476       Current = OffloadBuilder.addDeviceDependencesToHostAction(
3477           Current, InputArg, Phase, PL.back(), FullPL);
3478       if (!Current)
3479         break;
3480 
3481       // Queue linker inputs.
3482       if (Phase == phases::Link) {
3483         assert(Phase == PL.back() && "linking must be final compilation step.");
3484         LinkerInputs.push_back(Current);
3485         Current = nullptr;
3486         break;
3487       }
3488 
3489       // TODO: Consider removing this because the merged may not end up being
3490       // the final Phase in the pipeline. Perhaps the merged could just merge
3491       // and then pass an artifact of some sort to the Link Phase.
3492       // Queue merger inputs.
3493       if (Phase == phases::IfsMerge) {
3494         assert(Phase == PL.back() && "merging must be final compilation step.");
3495         MergerInputs.push_back(Current);
3496         Current = nullptr;
3497         break;
3498       }
3499 
3500       // Each precompiled header file after a module file action is a module
3501       // header of that same module file, rather than being compiled to a
3502       // separate PCH.
3503       if (Phase == phases::Precompile && HeaderModuleAction &&
3504           getPrecompiledType(InputType) == types::TY_PCH) {
3505         HeaderModuleAction->addModuleHeaderInput(Current);
3506         Current = nullptr;
3507         break;
3508       }
3509 
3510       // FIXME: Should we include any prior module file outputs as inputs of
3511       // later actions in the same command line?
3512 
3513       // Otherwise construct the appropriate action.
3514       Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3515 
3516       // We didn't create a new action, so we will just move to the next phase.
3517       if (NewCurrent == Current)
3518         continue;
3519 
3520       if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3521         HeaderModuleAction = HMA;
3522 
3523       Current = NewCurrent;
3524 
3525       // Use the current host action in any of the offloading actions, if
3526       // required.
3527       if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3528         break;
3529 
3530       if (Current->getType() == types::TY_Nothing)
3531         break;
3532     }
3533 
3534     // If we ended with something, add to the output list.
3535     if (Current)
3536       Actions.push_back(Current);
3537 
3538     // Add any top level actions generated for offloading.
3539     OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3540   }
3541 
3542   // Add a link action if necessary.
3543   if (!LinkerInputs.empty()) {
3544     if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
3545       LinkerInputs.push_back(Wrapper);
3546     Action *LA;
3547     // Check if this Linker Job should emit a static library.
3548     if (ShouldEmitStaticLibrary(Args)) {
3549       LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
3550     } else {
3551       LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3552     }
3553     LA = OffloadBuilder.processHostLinkAction(LA);
3554     Actions.push_back(LA);
3555   }
3556 
3557   // Add an interface stubs merge action if necessary.
3558   if (!MergerInputs.empty())
3559     Actions.push_back(
3560         C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3561 
3562   if (Args.hasArg(options::OPT_emit_interface_stubs)) {
3563     auto PhaseList = types::getCompilationPhases(
3564         types::TY_IFS_CPP,
3565         Args.hasArg(options::OPT_c) ? phases::Compile : phases::LastPhase);
3566 
3567     ActionList MergerInputs;
3568 
3569     for (auto &I : Inputs) {
3570       types::ID InputType = I.first;
3571       const Arg *InputArg = I.second;
3572 
3573       // Currently clang and the llvm assembler do not support generating symbol
3574       // stubs from assembly, so we skip the input on asm files. For ifs files
3575       // we rely on the normal pipeline setup in the pipeline setup code above.
3576       if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
3577           InputType == types::TY_Asm)
3578         continue;
3579 
3580       Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3581 
3582       for (auto Phase : PhaseList) {
3583         switch (Phase) {
3584         default:
3585           llvm_unreachable(
3586               "IFS Pipeline can only consist of Compile followed by IfsMerge.");
3587         case phases::Compile: {
3588           // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
3589           // files where the .o file is located. The compile action can not
3590           // handle this.
3591           if (InputType == types::TY_Object)
3592             break;
3593 
3594           Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
3595           break;
3596         }
3597         case phases::IfsMerge: {
3598           assert(Phase == PhaseList.back() &&
3599                  "merging must be final compilation step.");
3600           MergerInputs.push_back(Current);
3601           Current = nullptr;
3602           break;
3603         }
3604         }
3605       }
3606 
3607       // If we ended with something, add to the output list.
3608       if (Current)
3609         Actions.push_back(Current);
3610     }
3611 
3612     // Add an interface stubs merge action if necessary.
3613     if (!MergerInputs.empty())
3614       Actions.push_back(
3615           C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3616   }
3617 
3618   // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
3619   // Compile phase that prints out supported cpu models and quits.
3620   if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
3621     // Use the -mcpu=? flag as the dummy input to cc1.
3622     Actions.clear();
3623     Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
3624     Actions.push_back(
3625         C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
3626     for (auto &I : Inputs)
3627       I.second->claim();
3628   }
3629 
3630   // Claim ignored clang-cl options.
3631   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3632 
3633   // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3634   // to non-CUDA compilations and should not trigger warnings there.
3635   Args.ClaimAllArgs(options::OPT_cuda_host_only);
3636   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3637 }
3638 
3639 Action *Driver::ConstructPhaseAction(
3640     Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3641     Action::OffloadKind TargetDeviceOffloadKind) const {
3642   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3643 
3644   // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3645   // encode this in the steps because the intermediate type depends on
3646   // arguments. Just special case here.
3647   if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3648     return Input;
3649 
3650   // Build the appropriate action.
3651   switch (Phase) {
3652   case phases::Link:
3653     llvm_unreachable("link action invalid here.");
3654   case phases::IfsMerge:
3655     llvm_unreachable("ifsmerge action invalid here.");
3656   case phases::Preprocess: {
3657     types::ID OutputTy;
3658     // -M and -MM specify the dependency file name by altering the output type,
3659     // -if -MD and -MMD are not specified.
3660     if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
3661         !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
3662       OutputTy = types::TY_Dependencies;
3663     } else {
3664       OutputTy = Input->getType();
3665       if (!Args.hasFlag(options::OPT_frewrite_includes,
3666                         options::OPT_fno_rewrite_includes, false) &&
3667           !Args.hasFlag(options::OPT_frewrite_imports,
3668                         options::OPT_fno_rewrite_imports, false) &&
3669           !CCGenDiagnostics)
3670         OutputTy = types::getPreprocessedType(OutputTy);
3671       assert(OutputTy != types::TY_INVALID &&
3672              "Cannot preprocess this input type!");
3673     }
3674     return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3675   }
3676   case phases::Precompile: {
3677     types::ID OutputTy = getPrecompiledType(Input->getType());
3678     assert(OutputTy != types::TY_INVALID &&
3679            "Cannot precompile this input type!");
3680 
3681     // If we're given a module name, precompile header file inputs as a
3682     // module, not as a precompiled header.
3683     const char *ModName = nullptr;
3684     if (OutputTy == types::TY_PCH) {
3685       if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3686         ModName = A->getValue();
3687       if (ModName)
3688         OutputTy = types::TY_ModuleFile;
3689     }
3690 
3691     if (Args.hasArg(options::OPT_fsyntax_only)) {
3692       // Syntax checks should not emit a PCH file
3693       OutputTy = types::TY_Nothing;
3694     }
3695 
3696     if (ModName)
3697       return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3698                                                            ModName);
3699     return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3700   }
3701   case phases::Compile: {
3702     if (Args.hasArg(options::OPT_fsyntax_only))
3703       return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3704     if (Args.hasArg(options::OPT_rewrite_objc))
3705       return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3706     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3707       return C.MakeAction<CompileJobAction>(Input,
3708                                             types::TY_RewrittenLegacyObjC);
3709     if (Args.hasArg(options::OPT__analyze))
3710       return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3711     if (Args.hasArg(options::OPT__migrate))
3712       return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3713     if (Args.hasArg(options::OPT_emit_ast))
3714       return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3715     if (Args.hasArg(options::OPT_module_file_info))
3716       return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3717     if (Args.hasArg(options::OPT_verify_pch))
3718       return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3719     return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3720   }
3721   case phases::Backend: {
3722     if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
3723       types::ID Output =
3724           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
3725       return C.MakeAction<BackendJobAction>(Input, Output);
3726     }
3727     if (Args.hasArg(options::OPT_emit_llvm) ||
3728         (TargetDeviceOffloadKind == Action::OFK_HIP &&
3729          Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
3730                       false))) {
3731       types::ID Output =
3732           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
3733       return C.MakeAction<BackendJobAction>(Input, Output);
3734     }
3735     return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
3736   }
3737   case phases::Assemble:
3738     return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
3739   }
3740 
3741   llvm_unreachable("invalid phase in ConstructPhaseAction");
3742 }
3743 
3744 void Driver::BuildJobs(Compilation &C) const {
3745   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3746 
3747   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3748 
3749   // It is an error to provide a -o option if we are making multiple output
3750   // files. There are exceptions:
3751   //
3752   // IfsMergeJob: when generating interface stubs enabled we want to be able to
3753   // generate the stub file at the same time that we generate the real
3754   // library/a.out. So when a .o, .so, etc are the output, with clang interface
3755   // stubs there will also be a .ifs and .ifso at the same location.
3756   //
3757   // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
3758   // and -c is passed, we still want to be able to generate a .ifs file while
3759   // we are also generating .o files. So we allow more than one output file in
3760   // this case as well.
3761   //
3762   if (FinalOutput) {
3763     unsigned NumOutputs = 0;
3764     unsigned NumIfsOutputs = 0;
3765     for (const Action *A : C.getActions())
3766       if (A->getType() != types::TY_Nothing &&
3767           !(A->getKind() == Action::IfsMergeJobClass ||
3768             (A->getType() == clang::driver::types::TY_IFS_CPP &&
3769              A->getKind() == clang::driver::Action::CompileJobClass &&
3770              0 == NumIfsOutputs++) ||
3771             (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
3772              A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
3773         ++NumOutputs;
3774 
3775     if (NumOutputs > 1) {
3776       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
3777       FinalOutput = nullptr;
3778     }
3779   }
3780 
3781   // Collect the list of architectures.
3782   llvm::StringSet<> ArchNames;
3783   if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3784     for (const Arg *A : C.getArgs())
3785       if (A->getOption().matches(options::OPT_arch))
3786         ArchNames.insert(A->getValue());
3787 
3788   // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3789   std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
3790   for (Action *A : C.getActions()) {
3791     // If we are linking an image for multiple archs then the linker wants
3792     // -arch_multiple and -final_output <final image name>. Unfortunately, this
3793     // doesn't fit in cleanly because we have to pass this information down.
3794     //
3795     // FIXME: This is a hack; find a cleaner way to integrate this into the
3796     // process.
3797     const char *LinkingOutput = nullptr;
3798     if (isa<LipoJobAction>(A)) {
3799       if (FinalOutput)
3800         LinkingOutput = FinalOutput->getValue();
3801       else
3802         LinkingOutput = getDefaultImageName();
3803     }
3804 
3805     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
3806                        /*BoundArch*/ StringRef(),
3807                        /*AtTopLevel*/ true,
3808                        /*MultipleArchs*/ ArchNames.size() > 1,
3809                        /*LinkingOutput*/ LinkingOutput, CachedResults,
3810                        /*TargetDeviceOffloadKind*/ Action::OFK_None);
3811   }
3812 
3813   // If we have more than one job, then disable integrated-cc1 for now.
3814   if (C.getJobs().size() > 1)
3815     for (auto &J : C.getJobs())
3816       J.InProcess = false;
3817 
3818   // If the user passed -Qunused-arguments or there were errors, don't warn
3819   // about any unused arguments.
3820   if (Diags.hasErrorOccurred() ||
3821       C.getArgs().hasArg(options::OPT_Qunused_arguments))
3822     return;
3823 
3824   // Claim -### here.
3825   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
3826 
3827   // Claim --driver-mode, --rsp-quoting, it was handled earlier.
3828   (void)C.getArgs().hasArg(options::OPT_driver_mode);
3829   (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
3830 
3831   for (Arg *A : C.getArgs()) {
3832     // FIXME: It would be nice to be able to send the argument to the
3833     // DiagnosticsEngine, so that extra values, position, and so on could be
3834     // printed.
3835     if (!A->isClaimed()) {
3836       if (A->getOption().hasFlag(options::NoArgumentUnused))
3837         continue;
3838 
3839       // Suppress the warning automatically if this is just a flag, and it is an
3840       // instance of an argument we already claimed.
3841       const Option &Opt = A->getOption();
3842       if (Opt.getKind() == Option::FlagClass) {
3843         bool DuplicateClaimed = false;
3844 
3845         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3846           if (AA->isClaimed()) {
3847             DuplicateClaimed = true;
3848             break;
3849           }
3850         }
3851 
3852         if (DuplicateClaimed)
3853           continue;
3854       }
3855 
3856       // In clang-cl, don't mention unknown arguments here since they have
3857       // already been warned about.
3858       if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3859         Diag(clang::diag::warn_drv_unused_argument)
3860             << A->getAsString(C.getArgs());
3861     }
3862   }
3863 }
3864 
3865 namespace {
3866 /// Utility class to control the collapse of dependent actions and select the
3867 /// tools accordingly.
3868 class ToolSelector final {
3869   /// The tool chain this selector refers to.
3870   const ToolChain &TC;
3871 
3872   /// The compilation this selector refers to.
3873   const Compilation &C;
3874 
3875   /// The base action this selector refers to.
3876   const JobAction *BaseAction;
3877 
3878   /// Set to true if the current toolchain refers to host actions.
3879   bool IsHostSelector;
3880 
3881   /// Set to true if save-temps and embed-bitcode functionalities are active.
3882   bool SaveTemps;
3883   bool EmbedBitcode;
3884 
3885   /// Get previous dependent action or null if that does not exist. If
3886   /// \a CanBeCollapsed is false, that action must be legal to collapse or
3887   /// null will be returned.
3888   const JobAction *getPrevDependentAction(const ActionList &Inputs,
3889                                           ActionList &SavedOffloadAction,
3890                                           bool CanBeCollapsed = true) {
3891     // An option can be collapsed only if it has a single input.
3892     if (Inputs.size() != 1)
3893       return nullptr;
3894 
3895     Action *CurAction = *Inputs.begin();
3896     if (CanBeCollapsed &&
3897         !CurAction->isCollapsingWithNextDependentActionLegal())
3898       return nullptr;
3899 
3900     // If the input action is an offload action. Look through it and save any
3901     // offload action that can be dropped in the event of a collapse.
3902     if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3903       // If the dependent action is a device action, we will attempt to collapse
3904       // only with other device actions. Otherwise, we would do the same but
3905       // with host actions only.
3906       if (!IsHostSelector) {
3907         if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3908           CurAction =
3909               OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3910           if (CanBeCollapsed &&
3911               !CurAction->isCollapsingWithNextDependentActionLegal())
3912             return nullptr;
3913           SavedOffloadAction.push_back(OA);
3914           return dyn_cast<JobAction>(CurAction);
3915         }
3916       } else if (OA->hasHostDependence()) {
3917         CurAction = OA->getHostDependence();
3918         if (CanBeCollapsed &&
3919             !CurAction->isCollapsingWithNextDependentActionLegal())
3920           return nullptr;
3921         SavedOffloadAction.push_back(OA);
3922         return dyn_cast<JobAction>(CurAction);
3923       }
3924       return nullptr;
3925     }
3926 
3927     return dyn_cast<JobAction>(CurAction);
3928   }
3929 
3930   /// Return true if an assemble action can be collapsed.
3931   bool canCollapseAssembleAction() const {
3932     return TC.useIntegratedAs() && !SaveTemps &&
3933            !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3934            !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3935            !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3936   }
3937 
3938   /// Return true if a preprocessor action can be collapsed.
3939   bool canCollapsePreprocessorAction() const {
3940     return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3941            !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3942            !C.getArgs().hasArg(options::OPT_rewrite_objc);
3943   }
3944 
3945   /// Struct that relates an action with the offload actions that would be
3946   /// collapsed with it.
3947   struct JobActionInfo final {
3948     /// The action this info refers to.
3949     const JobAction *JA = nullptr;
3950     /// The offload actions we need to take care off if this action is
3951     /// collapsed.
3952     ActionList SavedOffloadAction;
3953   };
3954 
3955   /// Append collapsed offload actions from the give nnumber of elements in the
3956   /// action info array.
3957   static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3958                                            ArrayRef<JobActionInfo> &ActionInfo,
3959                                            unsigned ElementNum) {
3960     assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3961     for (unsigned I = 0; I < ElementNum; ++I)
3962       CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3963                                     ActionInfo[I].SavedOffloadAction.end());
3964   }
3965 
3966   /// Functions that attempt to perform the combining. They detect if that is
3967   /// legal, and if so they update the inputs \a Inputs and the offload action
3968   /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3969   /// the combined action is returned. If the combining is not legal or if the
3970   /// tool does not exist, null is returned.
3971   /// Currently three kinds of collapsing are supported:
3972   ///  - Assemble + Backend + Compile;
3973   ///  - Assemble + Backend ;
3974   ///  - Backend + Compile.
3975   const Tool *
3976   combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3977                                 ActionList &Inputs,
3978                                 ActionList &CollapsedOffloadAction) {
3979     if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3980       return nullptr;
3981     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3982     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3983     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3984     if (!AJ || !BJ || !CJ)
3985       return nullptr;
3986 
3987     // Get compiler tool.
3988     const Tool *T = TC.SelectTool(*CJ);
3989     if (!T)
3990       return nullptr;
3991 
3992     // When using -fembed-bitcode, it is required to have the same tool (clang)
3993     // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3994     if (EmbedBitcode) {
3995       const Tool *BT = TC.SelectTool(*BJ);
3996       if (BT == T)
3997         return nullptr;
3998     }
3999 
4000     if (!T->hasIntegratedAssembler())
4001       return nullptr;
4002 
4003     Inputs = CJ->getInputs();
4004     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4005                                  /*NumElements=*/3);
4006     return T;
4007   }
4008   const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4009                                      ActionList &Inputs,
4010                                      ActionList &CollapsedOffloadAction) {
4011     if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
4012       return nullptr;
4013     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4014     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4015     if (!AJ || !BJ)
4016       return nullptr;
4017 
4018     // Get backend tool.
4019     const Tool *T = TC.SelectTool(*BJ);
4020     if (!T)
4021       return nullptr;
4022 
4023     if (!T->hasIntegratedAssembler())
4024       return nullptr;
4025 
4026     Inputs = BJ->getInputs();
4027     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4028                                  /*NumElements=*/2);
4029     return T;
4030   }
4031   const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4032                                     ActionList &Inputs,
4033                                     ActionList &CollapsedOffloadAction) {
4034     if (ActionInfo.size() < 2)
4035       return nullptr;
4036     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4037     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4038     if (!BJ || !CJ)
4039       return nullptr;
4040 
4041     // Check if the initial input (to the compile job or its predessor if one
4042     // exists) is LLVM bitcode. In that case, no preprocessor step is required
4043     // and we can still collapse the compile and backend jobs when we have
4044     // -save-temps. I.e. there is no need for a separate compile job just to
4045     // emit unoptimized bitcode.
4046     bool InputIsBitcode = true;
4047     for (size_t i = 1; i < ActionInfo.size(); i++)
4048       if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
4049           ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
4050         InputIsBitcode = false;
4051         break;
4052       }
4053     if (!InputIsBitcode && !canCollapsePreprocessorAction())
4054       return nullptr;
4055 
4056     // Get compiler tool.
4057     const Tool *T = TC.SelectTool(*CJ);
4058     if (!T)
4059       return nullptr;
4060 
4061     if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
4062       return nullptr;
4063 
4064     Inputs = CJ->getInputs();
4065     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4066                                  /*NumElements=*/2);
4067     return T;
4068   }
4069 
4070   /// Updates the inputs if the obtained tool supports combining with
4071   /// preprocessor action, and the current input is indeed a preprocessor
4072   /// action. If combining results in the collapse of offloading actions, those
4073   /// are appended to \a CollapsedOffloadAction.
4074   void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4075                                ActionList &CollapsedOffloadAction) {
4076     if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
4077       return;
4078 
4079     // Attempt to get a preprocessor action dependence.
4080     ActionList PreprocessJobOffloadActions;
4081     ActionList NewInputs;
4082     for (Action *A : Inputs) {
4083       auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4084       if (!PJ || !isa<PreprocessJobAction>(PJ)) {
4085         NewInputs.push_back(A);
4086         continue;
4087       }
4088 
4089       // This is legal to combine. Append any offload action we found and add the
4090       // current input to preprocessor inputs.
4091       CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
4092                                     PreprocessJobOffloadActions.end());
4093       NewInputs.append(PJ->input_begin(), PJ->input_end());
4094     }
4095     Inputs = NewInputs;
4096   }
4097 
4098 public:
4099   ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
4100                const Compilation &C, bool SaveTemps, bool EmbedBitcode)
4101       : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
4102         EmbedBitcode(EmbedBitcode) {
4103     assert(BaseAction && "Invalid base action.");
4104     IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
4105   }
4106 
4107   /// Check if a chain of actions can be combined and return the tool that can
4108   /// handle the combination of actions. The pointer to the current inputs \a
4109   /// Inputs and the list of offload actions \a CollapsedOffloadActions
4110   /// connected to collapsed actions are updated accordingly. The latter enables
4111   /// the caller of the selector to process them afterwards instead of just
4112   /// dropping them. If no suitable tool is found, null will be returned.
4113   const Tool *getTool(ActionList &Inputs,
4114                       ActionList &CollapsedOffloadAction) {
4115     //
4116     // Get the largest chain of actions that we could combine.
4117     //
4118 
4119     SmallVector<JobActionInfo, 5> ActionChain(1);
4120     ActionChain.back().JA = BaseAction;
4121     while (ActionChain.back().JA) {
4122       const Action *CurAction = ActionChain.back().JA;
4123 
4124       // Grow the chain by one element.
4125       ActionChain.resize(ActionChain.size() + 1);
4126       JobActionInfo &AI = ActionChain.back();
4127 
4128       // Attempt to fill it with the
4129       AI.JA =
4130           getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
4131     }
4132 
4133     // Pop the last action info as it could not be filled.
4134     ActionChain.pop_back();
4135 
4136     //
4137     // Attempt to combine actions. If all combining attempts failed, just return
4138     // the tool of the provided action. At the end we attempt to combine the
4139     // action with any preprocessor action it may depend on.
4140     //
4141 
4142     const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
4143                                                   CollapsedOffloadAction);
4144     if (!T)
4145       T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
4146     if (!T)
4147       T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
4148     if (!T) {
4149       Inputs = BaseAction->getInputs();
4150       T = TC.SelectTool(*BaseAction);
4151     }
4152 
4153     combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
4154     return T;
4155   }
4156 };
4157 }
4158 
4159 /// Return a string that uniquely identifies the result of a job. The bound arch
4160 /// is not necessarily represented in the toolchain's triple -- for example,
4161 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
4162 /// Also, we need to add the offloading device kind, as the same tool chain can
4163 /// be used for host and device for some programming models, e.g. OpenMP.
4164 static std::string GetTriplePlusArchString(const ToolChain *TC,
4165                                            StringRef BoundArch,
4166                                            Action::OffloadKind OffloadKind) {
4167   std::string TriplePlusArch = TC->getTriple().normalize();
4168   if (!BoundArch.empty()) {
4169     TriplePlusArch += "-";
4170     TriplePlusArch += BoundArch;
4171   }
4172   TriplePlusArch += "-";
4173   TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
4174   return TriplePlusArch;
4175 }
4176 
4177 InputInfo Driver::BuildJobsForAction(
4178     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4179     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4180     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4181     Action::OffloadKind TargetDeviceOffloadKind) const {
4182   std::pair<const Action *, std::string> ActionTC = {
4183       A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4184   auto CachedResult = CachedResults.find(ActionTC);
4185   if (CachedResult != CachedResults.end()) {
4186     return CachedResult->second;
4187   }
4188   InputInfo Result = BuildJobsForActionNoCache(
4189       C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
4190       CachedResults, TargetDeviceOffloadKind);
4191   CachedResults[ActionTC] = Result;
4192   return Result;
4193 }
4194 
4195 InputInfo Driver::BuildJobsForActionNoCache(
4196     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4197     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4198     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4199     Action::OffloadKind TargetDeviceOffloadKind) const {
4200   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4201 
4202   InputInfoList OffloadDependencesInputInfo;
4203   bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
4204   if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
4205     // The 'Darwin' toolchain is initialized only when its arguments are
4206     // computed. Get the default arguments for OFK_None to ensure that
4207     // initialization is performed before processing the offload action.
4208     // FIXME: Remove when darwin's toolchain is initialized during construction.
4209     C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
4210 
4211     // The offload action is expected to be used in four different situations.
4212     //
4213     // a) Set a toolchain/architecture/kind for a host action:
4214     //    Host Action 1 -> OffloadAction -> Host Action 2
4215     //
4216     // b) Set a toolchain/architecture/kind for a device action;
4217     //    Device Action 1 -> OffloadAction -> Device Action 2
4218     //
4219     // c) Specify a device dependence to a host action;
4220     //    Device Action 1  _
4221     //                      \
4222     //      Host Action 1  ---> OffloadAction -> Host Action 2
4223     //
4224     // d) Specify a host dependence to a device action.
4225     //      Host Action 1  _
4226     //                      \
4227     //    Device Action 1  ---> OffloadAction -> Device Action 2
4228     //
4229     // For a) and b), we just return the job generated for the dependence. For
4230     // c) and d) we override the current action with the host/device dependence
4231     // if the current toolchain is host/device and set the offload dependences
4232     // info with the jobs obtained from the device/host dependence(s).
4233 
4234     // If there is a single device option, just generate the job for it.
4235     if (OA->hasSingleDeviceDependence()) {
4236       InputInfo DevA;
4237       OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
4238                                        const char *DepBoundArch) {
4239         DevA =
4240             BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
4241                                /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
4242                                CachedResults, DepA->getOffloadingDeviceKind());
4243       });
4244       return DevA;
4245     }
4246 
4247     // If 'Action 2' is host, we generate jobs for the device dependences and
4248     // override the current action with the host dependence. Otherwise, we
4249     // generate the host dependences and override the action with the device
4250     // dependence. The dependences can't therefore be a top-level action.
4251     OA->doOnEachDependence(
4252         /*IsHostDependence=*/BuildingForOffloadDevice,
4253         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4254           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4255               C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
4256               /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
4257               DepA->getOffloadingDeviceKind()));
4258         });
4259 
4260     A = BuildingForOffloadDevice
4261             ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
4262             : OA->getHostDependence();
4263   }
4264 
4265   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
4266     // FIXME: It would be nice to not claim this here; maybe the old scheme of
4267     // just using Args was better?
4268     const Arg &Input = IA->getInputArg();
4269     Input.claim();
4270     if (Input.getOption().matches(options::OPT_INPUT)) {
4271       const char *Name = Input.getValue();
4272       return InputInfo(A, Name, /* _BaseInput = */ Name);
4273     }
4274     return InputInfo(A, &Input, /* _BaseInput = */ "");
4275   }
4276 
4277   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
4278     const ToolChain *TC;
4279     StringRef ArchName = BAA->getArchName();
4280 
4281     if (!ArchName.empty())
4282       TC = &getToolChain(C.getArgs(),
4283                          computeTargetTriple(*this, TargetTriple,
4284                                              C.getArgs(), ArchName));
4285     else
4286       TC = &C.getDefaultToolChain();
4287 
4288     return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
4289                               MultipleArchs, LinkingOutput, CachedResults,
4290                               TargetDeviceOffloadKind);
4291   }
4292 
4293 
4294   ActionList Inputs = A->getInputs();
4295 
4296   const JobAction *JA = cast<JobAction>(A);
4297   ActionList CollapsedOffloadActions;
4298 
4299   ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4300                   embedBitcodeInObject() && !isUsingLTO());
4301   const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4302 
4303   if (!T)
4304     return InputInfo();
4305 
4306   // If we've collapsed action list that contained OffloadAction we
4307   // need to build jobs for host/device-side inputs it may have held.
4308   for (const auto *OA : CollapsedOffloadActions)
4309     cast<OffloadAction>(OA)->doOnEachDependence(
4310         /*IsHostDependence=*/BuildingForOffloadDevice,
4311         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4312           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4313               C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
4314               /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
4315               DepA->getOffloadingDeviceKind()));
4316         });
4317 
4318   // Only use pipes when there is exactly one input.
4319   InputInfoList InputInfos;
4320   for (const Action *Input : Inputs) {
4321     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4322     // shouldn't get temporary output names.
4323     // FIXME: Clean this up.
4324     bool SubJobAtTopLevel =
4325         AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
4326     InputInfos.push_back(BuildJobsForAction(
4327         C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
4328         CachedResults, A->getOffloadingDeviceKind()));
4329   }
4330 
4331   // Always use the first input as the base input.
4332   const char *BaseInput = InputInfos[0].getBaseInput();
4333 
4334   // ... except dsymutil actions, which use their actual input as the base
4335   // input.
4336   if (JA->getType() == types::TY_dSYM)
4337     BaseInput = InputInfos[0].getFilename();
4338 
4339   // ... and in header module compilations, which use the module name.
4340   if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4341     BaseInput = ModuleJA->getModuleName();
4342 
4343   // Append outputs of offload device jobs to the input list
4344   if (!OffloadDependencesInputInfo.empty())
4345     InputInfos.append(OffloadDependencesInputInfo.begin(),
4346                       OffloadDependencesInputInfo.end());
4347 
4348   // Set the effective triple of the toolchain for the duration of this job.
4349   llvm::Triple EffectiveTriple;
4350   const ToolChain &ToolTC = T->getToolChain();
4351   const ArgList &Args =
4352       C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
4353   if (InputInfos.size() != 1) {
4354     EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4355   } else {
4356     // Pass along the input type if it can be unambiguously determined.
4357     EffectiveTriple = llvm::Triple(
4358         ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4359   }
4360   RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4361 
4362   // Determine the place to write output to, if any.
4363   InputInfo Result;
4364   InputInfoList UnbundlingResults;
4365   if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4366     // If we have an unbundling job, we need to create results for all the
4367     // outputs. We also update the results cache so that other actions using
4368     // this unbundling action can get the right results.
4369     for (auto &UI : UA->getDependentActionsInfo()) {
4370       assert(UI.DependentOffloadKind != Action::OFK_None &&
4371              "Unbundling with no offloading??");
4372 
4373       // Unbundling actions are never at the top level. When we generate the
4374       // offloading prefix, we also do that for the host file because the
4375       // unbundling action does not change the type of the output which can
4376       // cause a overwrite.
4377       std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4378           UI.DependentOffloadKind,
4379           UI.DependentToolChain->getTriple().normalize(),
4380           /*CreatePrefixForHost=*/true);
4381       auto CurI = InputInfo(
4382           UA,
4383           GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4384                              /*AtTopLevel=*/false,
4385                              MultipleArchs ||
4386                                  UI.DependentOffloadKind == Action::OFK_HIP,
4387                              OffloadingPrefix),
4388           BaseInput);
4389       // Save the unbundling result.
4390       UnbundlingResults.push_back(CurI);
4391 
4392       // Get the unique string identifier for this dependence and cache the
4393       // result.
4394       StringRef Arch;
4395       if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4396         if (UI.DependentOffloadKind == Action::OFK_Host)
4397           Arch = StringRef();
4398         else
4399           Arch = UI.DependentBoundArch;
4400       } else
4401         Arch = BoundArch;
4402 
4403       CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4404                                                 UI.DependentOffloadKind)}] =
4405           CurI;
4406     }
4407 
4408     // Now that we have all the results generated, select the one that should be
4409     // returned for the current depending action.
4410     std::pair<const Action *, std::string> ActionTC = {
4411         A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4412     assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4413            "Result does not exist??");
4414     Result = CachedResults[ActionTC];
4415   } else if (JA->getType() == types::TY_Nothing)
4416     Result = InputInfo(A, BaseInput);
4417   else {
4418     // We only have to generate a prefix for the host if this is not a top-level
4419     // action.
4420     std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4421         A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4422         /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4423             !AtTopLevel);
4424     if (isa<OffloadWrapperJobAction>(JA)) {
4425       OffloadingPrefix += "-wrapper";
4426       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4427         BaseInput = FinalOutput->getValue();
4428       else
4429         BaseInput = getDefaultImageName();
4430     }
4431     Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
4432                                              AtTopLevel, MultipleArchs,
4433                                              OffloadingPrefix),
4434                        BaseInput);
4435   }
4436 
4437   if (CCCPrintBindings && !CCGenDiagnostics) {
4438     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4439                  << " - \"" << T->getName() << "\", inputs: [";
4440     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4441       llvm::errs() << InputInfos[i].getAsString();
4442       if (i + 1 != e)
4443         llvm::errs() << ", ";
4444     }
4445     if (UnbundlingResults.empty())
4446       llvm::errs() << "], output: " << Result.getAsString() << "\n";
4447     else {
4448       llvm::errs() << "], outputs: [";
4449       for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4450         llvm::errs() << UnbundlingResults[i].getAsString();
4451         if (i + 1 != e)
4452           llvm::errs() << ", ";
4453       }
4454       llvm::errs() << "] \n";
4455     }
4456   } else {
4457     if (UnbundlingResults.empty())
4458       T->ConstructJob(
4459           C, *JA, Result, InputInfos,
4460           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4461           LinkingOutput);
4462     else
4463       T->ConstructJobMultipleOutputs(
4464           C, *JA, UnbundlingResults, InputInfos,
4465           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4466           LinkingOutput);
4467   }
4468   return Result;
4469 }
4470 
4471 const char *Driver::getDefaultImageName() const {
4472   llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4473   return Target.isOSWindows() ? "a.exe" : "a.out";
4474 }
4475 
4476 /// Create output filename based on ArgValue, which could either be a
4477 /// full filename, filename without extension, or a directory. If ArgValue
4478 /// does not provide a filename, then use BaseName, and use the extension
4479 /// suitable for FileType.
4480 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
4481                                         StringRef BaseName,
4482                                         types::ID FileType) {
4483   SmallString<128> Filename = ArgValue;
4484 
4485   if (ArgValue.empty()) {
4486     // If the argument is empty, output to BaseName in the current dir.
4487     Filename = BaseName;
4488   } else if (llvm::sys::path::is_separator(Filename.back())) {
4489     // If the argument is a directory, output to BaseName in that dir.
4490     llvm::sys::path::append(Filename, BaseName);
4491   }
4492 
4493   if (!llvm::sys::path::has_extension(ArgValue)) {
4494     // If the argument didn't provide an extension, then set it.
4495     const char *Extension = types::getTypeTempSuffix(FileType, true);
4496 
4497     if (FileType == types::TY_Image &&
4498         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4499       // The output file is a dll.
4500       Extension = "dll";
4501     }
4502 
4503     llvm::sys::path::replace_extension(Filename, Extension);
4504   }
4505 
4506   return Args.MakeArgString(Filename.c_str());
4507 }
4508 
4509 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
4510                                        const char *BaseInput,
4511                                        StringRef BoundArch, bool AtTopLevel,
4512                                        bool MultipleArchs,
4513                                        StringRef OffloadingPrefix) const {
4514   llvm::PrettyStackTraceString CrashInfo("Computing output path");
4515   // Output to a user requested destination?
4516   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
4517     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4518       return C.addResultFile(FinalOutput->getValue(), &JA);
4519   }
4520 
4521   // For /P, preprocess to file named after BaseInput.
4522   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4523     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4524     StringRef BaseName = llvm::sys::path::filename(BaseInput);
4525     StringRef NameArg;
4526     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
4527       NameArg = A->getValue();
4528     return C.addResultFile(
4529         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4530         &JA);
4531   }
4532 
4533   // Default to writing to stdout?
4534   if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
4535     return "-";
4536 
4537   // Is this the assembly listing for /FA?
4538   if (JA.getType() == types::TY_PP_Asm &&
4539       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4540        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4541     // Use /Fa and the input filename to determine the asm file name.
4542     StringRef BaseName = llvm::sys::path::filename(BaseInput);
4543     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4544     return C.addResultFile(
4545         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4546         &JA);
4547   }
4548 
4549   // Output to a temporary file?
4550   if ((!AtTopLevel && !isSaveTempsEnabled() &&
4551        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4552       CCGenDiagnostics) {
4553     StringRef Name = llvm::sys::path::filename(BaseInput);
4554     std::pair<StringRef, StringRef> Split = Name.split('.');
4555     SmallString<128> TmpName;
4556     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4557     Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4558     if (CCGenDiagnostics && A) {
4559       SmallString<128> CrashDirectory(A->getValue());
4560       if (!getVFS().exists(CrashDirectory))
4561         llvm::sys::fs::create_directories(CrashDirectory);
4562       llvm::sys::path::append(CrashDirectory, Split.first);
4563       const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4564       std::error_code EC = llvm::sys::fs::createUniqueFile(
4565           CrashDirectory + Middle + Suffix, TmpName);
4566       if (EC) {
4567         Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4568         return "";
4569       }
4570     } else {
4571       TmpName = GetTemporaryPath(Split.first, Suffix);
4572     }
4573     return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4574   }
4575 
4576   SmallString<128> BasePath(BaseInput);
4577   StringRef BaseName;
4578 
4579   // Dsymutil actions should use the full path.
4580   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
4581     BaseName = BasePath;
4582   else
4583     BaseName = llvm::sys::path::filename(BasePath);
4584 
4585   // Determine what the derived output name should be.
4586   const char *NamedOutput;
4587 
4588   if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
4589       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4590     // The /Fo or /o flag decides the object filename.
4591     StringRef Val =
4592         C.getArgs()
4593             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4594             ->getValue();
4595     NamedOutput =
4596         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4597   } else if (JA.getType() == types::TY_Image &&
4598              C.getArgs().hasArg(options::OPT__SLASH_Fe,
4599                                 options::OPT__SLASH_o)) {
4600     // The /Fe or /o flag names the linked file.
4601     StringRef Val =
4602         C.getArgs()
4603             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4604             ->getValue();
4605     NamedOutput =
4606         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
4607   } else if (JA.getType() == types::TY_Image) {
4608     if (IsCLMode()) {
4609       // clang-cl uses BaseName for the executable name.
4610       NamedOutput =
4611           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
4612     } else {
4613       SmallString<128> Output(getDefaultImageName());
4614       // HIP image for device compilation with -fno-gpu-rdc is per compilation
4615       // unit.
4616       bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4617                         !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
4618                                              options::OPT_fno_gpu_rdc, false);
4619       if (IsHIPNoRDC) {
4620         Output = BaseName;
4621         llvm::sys::path::replace_extension(Output, "");
4622       }
4623       Output += OffloadingPrefix;
4624       if (MultipleArchs && !BoundArch.empty()) {
4625         Output += "-";
4626         Output.append(BoundArch);
4627       }
4628       if (IsHIPNoRDC)
4629         Output += ".out";
4630       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
4631     }
4632   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
4633     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
4634   } else {
4635     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4636     assert(Suffix && "All types used for output should have a suffix.");
4637 
4638     std::string::size_type End = std::string::npos;
4639     if (!types::appendSuffixForType(JA.getType()))
4640       End = BaseName.rfind('.');
4641     SmallString<128> Suffixed(BaseName.substr(0, End));
4642     Suffixed += OffloadingPrefix;
4643     if (MultipleArchs && !BoundArch.empty()) {
4644       Suffixed += "-";
4645       Suffixed.append(BoundArch);
4646     }
4647     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4648     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4649     // optimized bitcode output.
4650     auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
4651                                      const llvm::opt::DerivedArgList &Args) {
4652       // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
4653       // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
4654       // phase.)
4655       return isa<CompileJobAction>(JA) &&
4656              JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4657              Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4658                           false);
4659     };
4660     if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
4661         (C.getArgs().hasArg(options::OPT_emit_llvm) ||
4662          IsHIPRDCInCompilePhase(JA, C.getArgs())))
4663       Suffixed += ".tmp";
4664     Suffixed += '.';
4665     Suffixed += Suffix;
4666     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4667   }
4668 
4669   // Prepend object file path if -save-temps=obj
4670   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4671       JA.getType() != types::TY_PCH) {
4672     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4673     SmallString<128> TempPath(FinalOutput->getValue());
4674     llvm::sys::path::remove_filename(TempPath);
4675     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4676     llvm::sys::path::append(TempPath, OutputFileName);
4677     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4678   }
4679 
4680   // If we're saving temps and the temp file conflicts with the input file,
4681   // then avoid overwriting input file.
4682   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
4683     bool SameFile = false;
4684     SmallString<256> Result;
4685     llvm::sys::fs::current_path(Result);
4686     llvm::sys::path::append(Result, BaseName);
4687     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4688     // Must share the same path to conflict.
4689     if (SameFile) {
4690       StringRef Name = llvm::sys::path::filename(BaseInput);
4691       std::pair<StringRef, StringRef> Split = Name.split('.');
4692       std::string TmpName = GetTemporaryPath(
4693           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
4694       return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4695     }
4696   }
4697 
4698   // As an annoying special case, PCH generation doesn't strip the pathname.
4699   if (JA.getType() == types::TY_PCH && !IsCLMode()) {
4700     llvm::sys::path::remove_filename(BasePath);
4701     if (BasePath.empty())
4702       BasePath = NamedOutput;
4703     else
4704       llvm::sys::path::append(BasePath, NamedOutput);
4705     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
4706   } else {
4707     return C.addResultFile(NamedOutput, &JA);
4708   }
4709 }
4710 
4711 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
4712   // Search for Name in a list of paths.
4713   auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4714       -> llvm::Optional<std::string> {
4715     // Respect a limited subset of the '-Bprefix' functionality in GCC by
4716     // attempting to use this prefix when looking for file paths.
4717     for (const auto &Dir : P) {
4718       if (Dir.empty())
4719         continue;
4720       SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4721       llvm::sys::path::append(P, Name);
4722       if (llvm::sys::fs::exists(Twine(P)))
4723         return std::string(P);
4724     }
4725     return None;
4726   };
4727 
4728   if (auto P = SearchPaths(PrefixDirs))
4729     return *P;
4730 
4731   SmallString<128> R(ResourceDir);
4732   llvm::sys::path::append(R, Name);
4733   if (llvm::sys::fs::exists(Twine(R)))
4734     return std::string(R.str());
4735 
4736   SmallString<128> P(TC.getCompilerRTPath());
4737   llvm::sys::path::append(P, Name);
4738   if (llvm::sys::fs::exists(Twine(P)))
4739     return std::string(P.str());
4740 
4741   SmallString<128> D(Dir);
4742   llvm::sys::path::append(D, "..", Name);
4743   if (llvm::sys::fs::exists(Twine(D)))
4744     return std::string(D.str());
4745 
4746   if (auto P = SearchPaths(TC.getLibraryPaths()))
4747     return *P;
4748 
4749   if (auto P = SearchPaths(TC.getFilePaths()))
4750     return *P;
4751 
4752   return std::string(Name);
4753 }
4754 
4755 void Driver::generatePrefixedToolNames(
4756     StringRef Tool, const ToolChain &TC,
4757     SmallVectorImpl<std::string> &Names) const {
4758   // FIXME: Needs a better variable than TargetTriple
4759   Names.emplace_back((TargetTriple + "-" + Tool).str());
4760   Names.emplace_back(Tool);
4761 
4762   // Allow the discovery of tools prefixed with LLVM's default target triple.
4763   std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4764   if (DefaultTargetTriple != TargetTriple)
4765     Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
4766 }
4767 
4768 static bool ScanDirForExecutable(SmallString<128> &Dir,
4769                                  const std::string &Name) {
4770   llvm::sys::path::append(Dir, Name);
4771   if (llvm::sys::fs::can_execute(Twine(Dir)))
4772     return true;
4773   llvm::sys::path::remove_filename(Dir);
4774   return false;
4775 }
4776 
4777 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
4778   SmallVector<std::string, 2> TargetSpecificExecutables;
4779   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4780 
4781   // Respect a limited subset of the '-Bprefix' functionality in GCC by
4782   // attempting to use this prefix when looking for program paths.
4783   for (const auto &PrefixDir : PrefixDirs) {
4784     if (llvm::sys::fs::is_directory(PrefixDir)) {
4785       SmallString<128> P(PrefixDir);
4786       for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4787         if (ScanDirForExecutable(P, TargetSpecificExecutable))
4788           return std::string(P.str());
4789     } else {
4790       SmallString<128> P((PrefixDir + Name).str());
4791       if (llvm::sys::fs::can_execute(Twine(P)))
4792         return std::string(P.str());
4793     }
4794   }
4795 
4796   const ToolChain::path_list &List = TC.getProgramPaths();
4797   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
4798     // For each possible name of the tool look for it in
4799     // program paths first, then the path.
4800     // Higher priority names will be first, meaning that
4801     // a higher priority name in the path will be found
4802     // instead of a lower priority name in the program path.
4803     // E.g. <triple>-gcc on the path will be found instead
4804     // of gcc in the program path
4805     for (const auto &Path : List) {
4806       SmallString<128> P(Path);
4807       if (ScanDirForExecutable(P, TargetSpecificExecutable))
4808         return std::string(P.str());
4809     }
4810 
4811     // Fall back to the path
4812     if (llvm::ErrorOr<std::string> P =
4813             llvm::sys::findProgramByName(TargetSpecificExecutable))
4814       return *P;
4815   }
4816 
4817   return std::string(Name);
4818 }
4819 
4820 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
4821   SmallString<128> Path;
4822   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
4823   if (EC) {
4824     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4825     return "";
4826   }
4827 
4828   return std::string(Path.str());
4829 }
4830 
4831 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
4832   SmallString<128> Path;
4833   std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
4834   if (EC) {
4835     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4836     return "";
4837   }
4838 
4839   return std::string(Path.str());
4840 }
4841 
4842 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4843   SmallString<128> Output;
4844   if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4845     // FIXME: If anybody needs it, implement this obscure rule:
4846     // "If you specify a directory without a file name, the default file name
4847     // is VCx0.pch., where x is the major version of Visual C++ in use."
4848     Output = FpArg->getValue();
4849 
4850     // "If you do not specify an extension as part of the path name, an
4851     // extension of .pch is assumed. "
4852     if (!llvm::sys::path::has_extension(Output))
4853       Output += ".pch";
4854   } else {
4855     if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4856       Output = YcArg->getValue();
4857     if (Output.empty())
4858       Output = BaseName;
4859     llvm::sys::path::replace_extension(Output, ".pch");
4860   }
4861   return std::string(Output.str());
4862 }
4863 
4864 const ToolChain &Driver::getToolChain(const ArgList &Args,
4865                                       const llvm::Triple &Target) const {
4866 
4867   auto &TC = ToolChains[Target.str()];
4868   if (!TC) {
4869     switch (Target.getOS()) {
4870     case llvm::Triple::AIX:
4871       TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
4872       break;
4873     case llvm::Triple::Haiku:
4874       TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
4875       break;
4876     case llvm::Triple::Ananas:
4877       TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
4878       break;
4879     case llvm::Triple::CloudABI:
4880       TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
4881       break;
4882     case llvm::Triple::Darwin:
4883     case llvm::Triple::MacOSX:
4884     case llvm::Triple::IOS:
4885     case llvm::Triple::TvOS:
4886     case llvm::Triple::WatchOS:
4887       TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
4888       break;
4889     case llvm::Triple::DragonFly:
4890       TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
4891       break;
4892     case llvm::Triple::OpenBSD:
4893       TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
4894       break;
4895     case llvm::Triple::NetBSD:
4896       TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
4897       break;
4898     case llvm::Triple::FreeBSD:
4899       TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
4900       break;
4901     case llvm::Triple::Minix:
4902       TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
4903       break;
4904     case llvm::Triple::Linux:
4905     case llvm::Triple::ELFIAMCU:
4906       if (Target.getArch() == llvm::Triple::hexagon)
4907         TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
4908                                                              Args);
4909       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4910                !Target.hasEnvironment())
4911         TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4912                                                               Args);
4913       else if (Target.getArch() == llvm::Triple::ppc ||
4914                Target.getArch() == llvm::Triple::ppc64 ||
4915                Target.getArch() == llvm::Triple::ppc64le)
4916         TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
4917                                                               Args);
4918       else if (Target.getArch() == llvm::Triple::ve)
4919         TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
4920 
4921       else
4922         TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
4923       break;
4924     case llvm::Triple::NaCl:
4925       TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
4926       break;
4927     case llvm::Triple::Fuchsia:
4928       TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
4929       break;
4930     case llvm::Triple::Solaris:
4931       TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
4932       break;
4933     case llvm::Triple::AMDHSA:
4934       TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
4935       break;
4936     case llvm::Triple::AMDPAL:
4937     case llvm::Triple::Mesa3D:
4938       TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
4939       break;
4940     case llvm::Triple::Win32:
4941       switch (Target.getEnvironment()) {
4942       default:
4943         if (Target.isOSBinFormatELF())
4944           TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4945         else if (Target.isOSBinFormatMachO())
4946           TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
4947         else
4948           TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4949         break;
4950       case llvm::Triple::GNU:
4951         TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
4952         break;
4953       case llvm::Triple::Itanium:
4954         TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4955                                                                   Args);
4956         break;
4957       case llvm::Triple::MSVC:
4958       case llvm::Triple::UnknownEnvironment:
4959         if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4960                 .startswith_lower("bfd"))
4961           TC = std::make_unique<toolchains::CrossWindowsToolChain>(
4962               *this, Target, Args);
4963         else
4964           TC =
4965               std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
4966         break;
4967       }
4968       break;
4969     case llvm::Triple::PS4:
4970       TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
4971       break;
4972     case llvm::Triple::Contiki:
4973       TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
4974       break;
4975     case llvm::Triple::Hurd:
4976       TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
4977       break;
4978     default:
4979       // Of these targets, Hexagon is the only one that might have
4980       // an OS of Linux, in which case it got handled above already.
4981       switch (Target.getArch()) {
4982       case llvm::Triple::tce:
4983         TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
4984         break;
4985       case llvm::Triple::tcele:
4986         TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
4987         break;
4988       case llvm::Triple::hexagon:
4989         TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
4990                                                              Args);
4991         break;
4992       case llvm::Triple::lanai:
4993         TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
4994         break;
4995       case llvm::Triple::xcore:
4996         TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
4997         break;
4998       case llvm::Triple::wasm32:
4999       case llvm::Triple::wasm64:
5000         TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
5001         break;
5002       case llvm::Triple::avr:
5003         TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
5004         break;
5005       case llvm::Triple::msp430:
5006         TC =
5007             std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
5008         break;
5009       case llvm::Triple::riscv32:
5010       case llvm::Triple::riscv64:
5011         TC = std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
5012         break;
5013       case llvm::Triple::ve:
5014         TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5015         break;
5016       default:
5017         if (Target.getVendor() == llvm::Triple::Myriad)
5018           TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
5019                                                               Args);
5020         else if (toolchains::BareMetal::handlesTarget(Target))
5021           TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
5022         else if (Target.isOSBinFormatELF())
5023           TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5024         else if (Target.isOSBinFormatMachO())
5025           TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5026         else
5027           TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5028       }
5029     }
5030   }
5031 
5032   // Intentionally omitted from the switch above: llvm::Triple::CUDA.  CUDA
5033   // compiles always need two toolchains, the CUDA toolchain and the host
5034   // toolchain.  So the only valid way to create a CUDA toolchain is via
5035   // CreateOffloadingDeviceToolChains.
5036 
5037   return *TC;
5038 }
5039 
5040 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
5041   // Say "no" if there is not exactly one input of a type clang understands.
5042   if (JA.size() != 1 ||
5043       !types::isAcceptedByClang((*JA.input_begin())->getType()))
5044     return false;
5045 
5046   // And say "no" if this is not a kind of action clang understands.
5047   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
5048       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5049     return false;
5050 
5051   return true;
5052 }
5053 
5054 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
5055   // Say "no" if there is not exactly one input of a type flang understands.
5056   if (JA.size() != 1 ||
5057       !types::isFortran((*JA.input_begin())->getType()))
5058     return false;
5059 
5060   // And say "no" if this is not a kind of action flang understands.
5061   if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5062     return false;
5063 
5064   return true;
5065 }
5066 
5067 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
5068   // Only emit static library if the flag is set explicitly.
5069   if (Args.hasArg(options::OPT_emit_static_lib))
5070     return true;
5071   return false;
5072 }
5073 
5074 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
5075 /// grouped values as integers. Numbers which are not provided are set to 0.
5076 ///
5077 /// \return True if the entire string was parsed (9.2), or all groups were
5078 /// parsed (10.3.5extrastuff).
5079 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
5080                                unsigned &Micro, bool &HadExtra) {
5081   HadExtra = false;
5082 
5083   Major = Minor = Micro = 0;
5084   if (Str.empty())
5085     return false;
5086 
5087   if (Str.consumeInteger(10, Major))
5088     return false;
5089   if (Str.empty())
5090     return true;
5091   if (Str[0] != '.')
5092     return false;
5093 
5094   Str = Str.drop_front(1);
5095 
5096   if (Str.consumeInteger(10, Minor))
5097     return false;
5098   if (Str.empty())
5099     return true;
5100   if (Str[0] != '.')
5101     return false;
5102   Str = Str.drop_front(1);
5103 
5104   if (Str.consumeInteger(10, Micro))
5105     return false;
5106   if (!Str.empty())
5107     HadExtra = true;
5108   return true;
5109 }
5110 
5111 /// Parse digits from a string \p Str and fulfill \p Digits with
5112 /// the parsed numbers. This method assumes that the max number of
5113 /// digits to look for is equal to Digits.size().
5114 ///
5115 /// \return True if the entire string was parsed and there are
5116 /// no extra characters remaining at the end.
5117 bool Driver::GetReleaseVersion(StringRef Str,
5118                                MutableArrayRef<unsigned> Digits) {
5119   if (Str.empty())
5120     return false;
5121 
5122   unsigned CurDigit = 0;
5123   while (CurDigit < Digits.size()) {
5124     unsigned Digit;
5125     if (Str.consumeInteger(10, Digit))
5126       return false;
5127     Digits[CurDigit] = Digit;
5128     if (Str.empty())
5129       return true;
5130     if (Str[0] != '.')
5131       return false;
5132     Str = Str.drop_front(1);
5133     CurDigit++;
5134   }
5135 
5136   // More digits than requested, bail out...
5137   return false;
5138 }
5139 
5140 std::pair<unsigned, unsigned>
5141 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
5142   unsigned IncludedFlagsBitmask = 0;
5143   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
5144 
5145   if (IsClCompatMode) {
5146     // Include CL and Core options.
5147     IncludedFlagsBitmask |= options::CLOption;
5148     IncludedFlagsBitmask |= options::CoreOption;
5149   } else {
5150     ExcludedFlagsBitmask |= options::CLOption;
5151   }
5152 
5153   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
5154 }
5155 
5156 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
5157   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
5158 }
5159 
5160 bool clang::driver::willEmitRemarks(const ArgList &Args) {
5161   // -fsave-optimization-record enables it.
5162   if (Args.hasFlag(options::OPT_fsave_optimization_record,
5163                    options::OPT_fno_save_optimization_record, false))
5164     return true;
5165 
5166   // -fsave-optimization-record=<format> enables it as well.
5167   if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5168                    options::OPT_fno_save_optimization_record, false))
5169     return true;
5170 
5171   // -foptimization-record-file alone enables it too.
5172   if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
5173                    options::OPT_fno_save_optimization_record, false))
5174     return true;
5175 
5176   // -foptimization-record-passes alone enables it too.
5177   if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
5178                    options::OPT_fno_save_optimization_record, false))
5179     return true;
5180   return false;
5181 }
5182