xref: /freebsd/contrib/llvm-project/clang/lib/Driver/Driver.cpp (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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 "ToolChains/AIX.h"
11 #include "ToolChains/AMDGPU.h"
12 #include "ToolChains/AMDGPUOpenMP.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/Arch/RISCV.h"
16 #include "ToolChains/BareMetal.h"
17 #include "ToolChains/CSKYToolChain.h"
18 #include "ToolChains/Clang.h"
19 #include "ToolChains/CloudABI.h"
20 #include "ToolChains/Contiki.h"
21 #include "ToolChains/CrossWindows.h"
22 #include "ToolChains/Cuda.h"
23 #include "ToolChains/Darwin.h"
24 #include "ToolChains/DragonFly.h"
25 #include "ToolChains/FreeBSD.h"
26 #include "ToolChains/Fuchsia.h"
27 #include "ToolChains/Gnu.h"
28 #include "ToolChains/HIPAMD.h"
29 #include "ToolChains/HIPSPV.h"
30 #include "ToolChains/HLSL.h"
31 #include "ToolChains/Haiku.h"
32 #include "ToolChains/Hexagon.h"
33 #include "ToolChains/Hurd.h"
34 #include "ToolChains/Lanai.h"
35 #include "ToolChains/Linux.h"
36 #include "ToolChains/MSP430.h"
37 #include "ToolChains/MSVC.h"
38 #include "ToolChains/MinGW.h"
39 #include "ToolChains/Minix.h"
40 #include "ToolChains/MipsLinux.h"
41 #include "ToolChains/Myriad.h"
42 #include "ToolChains/NaCl.h"
43 #include "ToolChains/NetBSD.h"
44 #include "ToolChains/OHOS.h"
45 #include "ToolChains/OpenBSD.h"
46 #include "ToolChains/PPCFreeBSD.h"
47 #include "ToolChains/PPCLinux.h"
48 #include "ToolChains/PS4CPU.h"
49 #include "ToolChains/RISCVToolchain.h"
50 #include "ToolChains/SPIRV.h"
51 #include "ToolChains/Solaris.h"
52 #include "ToolChains/TCE.h"
53 #include "ToolChains/VEToolchain.h"
54 #include "ToolChains/WebAssembly.h"
55 #include "ToolChains/XCore.h"
56 #include "ToolChains/ZOS.h"
57 #include "clang/Basic/TargetID.h"
58 #include "clang/Basic/Version.h"
59 #include "clang/Config/config.h"
60 #include "clang/Driver/Action.h"
61 #include "clang/Driver/Compilation.h"
62 #include "clang/Driver/DriverDiagnostic.h"
63 #include "clang/Driver/InputInfo.h"
64 #include "clang/Driver/Job.h"
65 #include "clang/Driver/Options.h"
66 #include "clang/Driver/Phases.h"
67 #include "clang/Driver/SanitizerArgs.h"
68 #include "clang/Driver/Tool.h"
69 #include "clang/Driver/ToolChain.h"
70 #include "clang/Driver/Types.h"
71 #include "llvm/ADT/ArrayRef.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/StringExtras.h"
74 #include "llvm/ADT/StringRef.h"
75 #include "llvm/ADT/StringSet.h"
76 #include "llvm/ADT/StringSwitch.h"
77 #include "llvm/Config/llvm-config.h"
78 #include "llvm/MC/TargetRegistry.h"
79 #include "llvm/Option/Arg.h"
80 #include "llvm/Option/ArgList.h"
81 #include "llvm/Option/OptSpecifier.h"
82 #include "llvm/Option/OptTable.h"
83 #include "llvm/Option/Option.h"
84 #include "llvm/Support/CommandLine.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/ExitCodes.h"
87 #include "llvm/Support/FileSystem.h"
88 #include "llvm/Support/FormatVariadic.h"
89 #include "llvm/Support/MD5.h"
90 #include "llvm/Support/Path.h"
91 #include "llvm/Support/PrettyStackTrace.h"
92 #include "llvm/Support/Process.h"
93 #include "llvm/Support/Program.h"
94 #include "llvm/Support/StringSaver.h"
95 #include "llvm/Support/VirtualFileSystem.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include "llvm/TargetParser/Host.h"
98 #include <cstdlib> // ::getenv
99 #include <map>
100 #include <memory>
101 #include <optional>
102 #include <set>
103 #include <utility>
104 #if LLVM_ON_UNIX
105 #include <unistd.h> // getpid
106 #endif
107 
108 using namespace clang::driver;
109 using namespace clang;
110 using namespace llvm::opt;
111 
112 static std::optional<llvm::Triple> getOffloadTargetTriple(const Driver &D,
113                                                           const ArgList &Args) {
114   auto OffloadTargets = Args.getAllArgValues(options::OPT_offload_EQ);
115   // Offload compilation flow does not support multiple targets for now. We
116   // need the HIPActionBuilder (and possibly the CudaActionBuilder{,Base}too)
117   // to support multiple tool chains first.
118   switch (OffloadTargets.size()) {
119   default:
120     D.Diag(diag::err_drv_only_one_offload_target_supported);
121     return std::nullopt;
122   case 0:
123     D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << "";
124     return std::nullopt;
125   case 1:
126     break;
127   }
128   return llvm::Triple(OffloadTargets[0]);
129 }
130 
131 static std::optional<llvm::Triple>
132 getNVIDIAOffloadTargetTriple(const Driver &D, const ArgList &Args,
133                              const llvm::Triple &HostTriple) {
134   if (!Args.hasArg(options::OPT_offload_EQ)) {
135     return llvm::Triple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
136                                                  : "nvptx-nvidia-cuda");
137   }
138   auto TT = getOffloadTargetTriple(D, Args);
139   if (TT && (TT->getArch() == llvm::Triple::spirv32 ||
140              TT->getArch() == llvm::Triple::spirv64)) {
141     if (Args.hasArg(options::OPT_emit_llvm))
142       return TT;
143     D.Diag(diag::err_drv_cuda_offload_only_emit_bc);
144     return std::nullopt;
145   }
146   D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
147   return std::nullopt;
148 }
149 static std::optional<llvm::Triple>
150 getHIPOffloadTargetTriple(const Driver &D, const ArgList &Args) {
151   if (!Args.hasArg(options::OPT_offload_EQ)) {
152     return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple.
153   }
154   auto TT = getOffloadTargetTriple(D, Args);
155   if (!TT)
156     return std::nullopt;
157   if (TT->getArch() == llvm::Triple::amdgcn &&
158       TT->getVendor() == llvm::Triple::AMD &&
159       TT->getOS() == llvm::Triple::AMDHSA)
160     return TT;
161   if (TT->getArch() == llvm::Triple::spirv64)
162     return TT;
163   D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
164   return std::nullopt;
165 }
166 
167 // static
168 std::string Driver::GetResourcesPath(StringRef BinaryPath,
169                                      StringRef CustomResourceDir) {
170   // Since the resource directory is embedded in the module hash, it's important
171   // that all places that need it call this function, so that they get the
172   // exact same string ("a/../b/" and "b/" get different hashes, for example).
173 
174   // Dir is bin/ or lib/, depending on where BinaryPath is.
175   std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
176 
177   SmallString<128> P(Dir);
178   if (CustomResourceDir != "") {
179     llvm::sys::path::append(P, CustomResourceDir);
180   } else {
181     // On Windows, libclang.dll is in bin/.
182     // On non-Windows, libclang.so/.dylib is in lib/.
183     // With a static-library build of libclang, LibClangPath will contain the
184     // path of the embedding binary, which for LLVM binaries will be in bin/.
185     // ../lib gets us to lib/ in both cases.
186     P = llvm::sys::path::parent_path(Dir);
187     // This search path is also created in the COFF driver of lld, so any
188     // changes here also needs to happen in lld/COFF/Driver.cpp
189     llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang",
190                             CLANG_VERSION_MAJOR_STRING);
191   }
192 
193   return std::string(P.str());
194 }
195 
196 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
197                DiagnosticsEngine &Diags, std::string Title,
198                IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
199     : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
200       SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
201       Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None),
202       ModulesModeCXX20(false), LTOMode(LTOK_None),
203       ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
204       DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
205       CCLogDiagnostics(false), CCGenDiagnostics(false),
206       CCPrintProcessStats(false), CCPrintInternalStats(false),
207       TargetTriple(TargetTriple), Saver(Alloc), PrependArg(nullptr),
208       CheckInputsExist(true), ProbePrecompiled(true),
209       SuppressMissingInputWarning(false) {
210   // Provide a sane fallback if no VFS is specified.
211   if (!this->VFS)
212     this->VFS = llvm::vfs::getRealFileSystem();
213 
214   Name = std::string(llvm::sys::path::filename(ClangExecutable));
215   Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
216   InstalledDir = Dir; // Provide a sensible default installed dir.
217 
218   if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) {
219     // Prepend InstalledDir if SysRoot is relative
220     SmallString<128> P(InstalledDir);
221     llvm::sys::path::append(P, SysRoot);
222     SysRoot = std::string(P);
223   }
224 
225 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
226   SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
227 #endif
228 #if defined(CLANG_CONFIG_FILE_USER_DIR)
229   {
230     SmallString<128> P;
231     llvm::sys::fs::expand_tilde(CLANG_CONFIG_FILE_USER_DIR, P);
232     UserConfigDir = static_cast<std::string>(P);
233   }
234 #endif
235 
236   // Compute the path to the resource directory.
237   ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
238 }
239 
240 void Driver::setDriverMode(StringRef Value) {
241   static const std::string OptName =
242       getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
243   if (auto M = llvm::StringSwitch<std::optional<DriverMode>>(Value)
244                    .Case("gcc", GCCMode)
245                    .Case("g++", GXXMode)
246                    .Case("cpp", CPPMode)
247                    .Case("cl", CLMode)
248                    .Case("flang", FlangMode)
249                    .Case("dxc", DXCMode)
250                    .Default(std::nullopt))
251     Mode = *M;
252   else
253     Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
254 }
255 
256 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
257                                      bool IsClCompatMode,
258                                      bool &ContainsError) {
259   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
260   ContainsError = false;
261 
262   unsigned IncludedFlagsBitmask;
263   unsigned ExcludedFlagsBitmask;
264   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
265       getIncludeExcludeOptionFlagMasks(IsClCompatMode);
266 
267   // Make sure that Flang-only options don't pollute the Clang output
268   // TODO: Make sure that Clang-only options don't pollute Flang output
269   if (!IsFlangMode())
270     ExcludedFlagsBitmask |= options::FlangOnlyOption;
271 
272   unsigned MissingArgIndex, MissingArgCount;
273   InputArgList Args =
274       getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
275                           IncludedFlagsBitmask, ExcludedFlagsBitmask);
276 
277   // Check for missing argument error.
278   if (MissingArgCount) {
279     Diag(diag::err_drv_missing_argument)
280         << Args.getArgString(MissingArgIndex) << MissingArgCount;
281     ContainsError |=
282         Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
283                                  SourceLocation()) > DiagnosticsEngine::Warning;
284   }
285 
286   // Check for unsupported options.
287   for (const Arg *A : Args) {
288     if (A->getOption().hasFlag(options::Unsupported)) {
289       unsigned DiagID;
290       auto ArgString = A->getAsString(Args);
291       std::string Nearest;
292       if (getOpts().findNearest(
293             ArgString, Nearest, IncludedFlagsBitmask,
294             ExcludedFlagsBitmask | options::Unsupported) > 1) {
295         DiagID = diag::err_drv_unsupported_opt;
296         Diag(DiagID) << ArgString;
297       } else {
298         DiagID = diag::err_drv_unsupported_opt_with_suggestion;
299         Diag(DiagID) << ArgString << Nearest;
300       }
301       ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
302                        DiagnosticsEngine::Warning;
303       continue;
304     }
305 
306     // Warn about -mcpu= without an argument.
307     if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
308       Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
309       ContainsError |= Diags.getDiagnosticLevel(
310                            diag::warn_drv_empty_joined_argument,
311                            SourceLocation()) > DiagnosticsEngine::Warning;
312     }
313   }
314 
315   for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
316     unsigned DiagID;
317     auto ArgString = A->getAsString(Args);
318     std::string Nearest;
319     if (getOpts().findNearest(ArgString, Nearest, IncludedFlagsBitmask,
320                               ExcludedFlagsBitmask) > 1) {
321       if (!IsCLMode() &&
322           getOpts().findExact(ArgString, Nearest, options::CC1Option)) {
323         DiagID = diag::err_drv_unknown_argument_with_suggestion;
324         Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
325       } else {
326         DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
327                             : diag::err_drv_unknown_argument;
328         Diags.Report(DiagID) << ArgString;
329       }
330     } else {
331       DiagID = IsCLMode()
332                    ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
333                    : diag::err_drv_unknown_argument_with_suggestion;
334       Diags.Report(DiagID) << ArgString << Nearest;
335     }
336     ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
337                      DiagnosticsEngine::Warning;
338   }
339 
340   for (const Arg *A : Args.filtered(options::OPT_o)) {
341     if (ArgStrings[A->getIndex()] == A->getSpelling())
342       continue;
343 
344     // Warn on joined arguments that are similar to a long argument.
345     std::string ArgString = ArgStrings[A->getIndex()];
346     std::string Nearest;
347     if (getOpts().findExact("-" + ArgString, Nearest, IncludedFlagsBitmask,
348                             ExcludedFlagsBitmask))
349       Diags.Report(diag::warn_drv_potentially_misspelled_joined_argument)
350           << A->getAsString(Args) << Nearest;
351   }
352 
353   return Args;
354 }
355 
356 // Determine which compilation mode we are in. We look for options which
357 // affect the phase, starting with the earliest phases, and record which
358 // option we used to determine the final phase.
359 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
360                                  Arg **FinalPhaseArg) const {
361   Arg *PhaseArg = nullptr;
362   phases::ID FinalPhase;
363 
364   // -{E,EP,P,M,MM} only run the preprocessor.
365   if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
366       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
367       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
368       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P)) ||
369       CCGenDiagnostics) {
370     FinalPhase = phases::Preprocess;
371 
372     // --precompile only runs up to precompilation.
373     // Options that cause the output of C++20 compiled module interfaces or
374     // header units have the same effect.
375   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
376              (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
377              (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
378                                         options::OPT_fmodule_header_EQ))) {
379     FinalPhase = phases::Precompile;
380     // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
381   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
382              (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
383              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
384              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
385              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
386              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
387              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
388              (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
389              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
390     FinalPhase = phases::Compile;
391 
392   // -S only runs up to the backend.
393   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
394     FinalPhase = phases::Backend;
395 
396   // -c compilation only runs up to the assembler.
397   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
398     FinalPhase = phases::Assemble;
399 
400   } else if ((PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))) {
401     FinalPhase = phases::IfsMerge;
402 
403   // Otherwise do everything.
404   } else
405     FinalPhase = phases::Link;
406 
407   if (FinalPhaseArg)
408     *FinalPhaseArg = PhaseArg;
409 
410   return FinalPhase;
411 }
412 
413 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
414                          StringRef Value, bool Claim = true) {
415   Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
416                    Args.getBaseArgs().MakeIndex(Value), Value.data());
417   Args.AddSynthesizedArg(A);
418   if (Claim)
419     A->claim();
420   return A;
421 }
422 
423 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
424   const llvm::opt::OptTable &Opts = getOpts();
425   DerivedArgList *DAL = new DerivedArgList(Args);
426 
427   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
428   bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
429   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
430   bool IgnoreUnused = false;
431   for (Arg *A : Args) {
432     if (IgnoreUnused)
433       A->claim();
434 
435     if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
436       IgnoreUnused = true;
437       continue;
438     }
439     if (A->getOption().matches(options::OPT_end_no_unused_arguments)) {
440       IgnoreUnused = false;
441       continue;
442     }
443 
444     // Unfortunately, we have to parse some forwarding options (-Xassembler,
445     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
446     // (assembler and preprocessor), or bypass a previous driver ('collect2').
447 
448     // Rewrite linker options, to replace --no-demangle with a custom internal
449     // option.
450     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
451          A->getOption().matches(options::OPT_Xlinker)) &&
452         A->containsValue("--no-demangle")) {
453       // Add the rewritten no-demangle argument.
454       DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
455 
456       // Add the remaining values as Xlinker arguments.
457       for (StringRef Val : A->getValues())
458         if (Val != "--no-demangle")
459           DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
460 
461       continue;
462     }
463 
464     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
465     // some build systems. We don't try to be complete here because we don't
466     // care to encourage this usage model.
467     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
468         (A->getValue(0) == StringRef("-MD") ||
469          A->getValue(0) == StringRef("-MMD"))) {
470       // Rewrite to -MD/-MMD along with -MF.
471       if (A->getValue(0) == StringRef("-MD"))
472         DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
473       else
474         DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
475       if (A->getNumValues() == 2)
476         DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
477       continue;
478     }
479 
480     // Rewrite reserved library names.
481     if (A->getOption().matches(options::OPT_l)) {
482       StringRef Value = A->getValue();
483 
484       // Rewrite unless -nostdlib is present.
485       if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
486           Value == "stdc++") {
487         DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
488         continue;
489       }
490 
491       // Rewrite unconditionally.
492       if (Value == "cc_kext") {
493         DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
494         continue;
495       }
496     }
497 
498     // Pick up inputs via the -- option.
499     if (A->getOption().matches(options::OPT__DASH_DASH)) {
500       A->claim();
501       for (StringRef Val : A->getValues())
502         DAL->append(MakeInputArg(*DAL, Opts, Val, false));
503       continue;
504     }
505 
506     DAL->append(A);
507   }
508 
509   // Enforce -static if -miamcu is present.
510   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
511     DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_static));
512 
513 // Add a default value of -mlinker-version=, if one was given and the user
514 // didn't specify one.
515 #if defined(HOST_LINK_VERSION)
516   if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
517       strlen(HOST_LINK_VERSION) > 0) {
518     DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
519                       HOST_LINK_VERSION);
520     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
521   }
522 #endif
523 
524   return DAL;
525 }
526 
527 /// Compute target triple from args.
528 ///
529 /// This routine provides the logic to compute a target triple from various
530 /// args passed to the driver and the default triple string.
531 static llvm::Triple computeTargetTriple(const Driver &D,
532                                         StringRef TargetTriple,
533                                         const ArgList &Args,
534                                         StringRef DarwinArchName = "") {
535   // FIXME: Already done in Compilation *Driver::BuildCompilation
536   if (const Arg *A = Args.getLastArg(options::OPT_target))
537     TargetTriple = A->getValue();
538 
539   llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
540 
541   // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
542   // -gnu* only, and we can not change this, so we have to detect that case as
543   // being the Hurd OS.
544   if (TargetTriple.contains("-unknown-gnu") || TargetTriple.contains("-pc-gnu"))
545     Target.setOSName("hurd");
546 
547   // Handle Apple-specific options available here.
548   if (Target.isOSBinFormatMachO()) {
549     // If an explicit Darwin arch name is given, that trumps all.
550     if (!DarwinArchName.empty()) {
551       tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName,
552                                                    Args);
553       return Target;
554     }
555 
556     // Handle the Darwin '-arch' flag.
557     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
558       StringRef ArchName = A->getValue();
559       tools::darwin::setTripleTypeForMachOArchName(Target, ArchName, Args);
560     }
561   }
562 
563   // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
564   // '-mbig-endian'/'-EB'.
565   if (Arg *A = Args.getLastArgNoClaim(options::OPT_mlittle_endian,
566                                       options::OPT_mbig_endian)) {
567     llvm::Triple T = A->getOption().matches(options::OPT_mlittle_endian)
568                          ? Target.getLittleEndianArchVariant()
569                          : Target.getBigEndianArchVariant();
570     if (T.getArch() != llvm::Triple::UnknownArch) {
571       Target = std::move(T);
572       Args.claimAllArgs(options::OPT_mlittle_endian, options::OPT_mbig_endian);
573     }
574   }
575 
576   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
577   if (Target.getArch() == llvm::Triple::tce ||
578       Target.getOS() == llvm::Triple::Minix)
579     return Target;
580 
581   // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
582   if (Target.isOSAIX()) {
583     if (std::optional<std::string> ObjectModeValue =
584             llvm::sys::Process::GetEnv("OBJECT_MODE")) {
585       StringRef ObjectMode = *ObjectModeValue;
586       llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
587 
588       if (ObjectMode.equals("64")) {
589         AT = Target.get64BitArchVariant().getArch();
590       } else if (ObjectMode.equals("32")) {
591         AT = Target.get32BitArchVariant().getArch();
592       } else {
593         D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
594       }
595 
596       if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
597         Target.setArch(AT);
598     }
599   }
600 
601   // The `-maix[32|64]` flags are only valid for AIX targets.
602   if (Arg *A = Args.getLastArgNoClaim(options::OPT_maix32, options::OPT_maix64);
603       A && !Target.isOSAIX())
604     D.Diag(diag::err_drv_unsupported_opt_for_target)
605         << A->getAsString(Args) << Target.str();
606 
607   // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
608   Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
609                            options::OPT_m32, options::OPT_m16,
610                            options::OPT_maix32, options::OPT_maix64);
611   if (A) {
612     llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
613 
614     if (A->getOption().matches(options::OPT_m64) ||
615         A->getOption().matches(options::OPT_maix64)) {
616       AT = Target.get64BitArchVariant().getArch();
617       if (Target.getEnvironment() == llvm::Triple::GNUX32)
618         Target.setEnvironment(llvm::Triple::GNU);
619       else if (Target.getEnvironment() == llvm::Triple::MuslX32)
620         Target.setEnvironment(llvm::Triple::Musl);
621     } else if (A->getOption().matches(options::OPT_mx32) &&
622                Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
623       AT = llvm::Triple::x86_64;
624       if (Target.getEnvironment() == llvm::Triple::Musl)
625         Target.setEnvironment(llvm::Triple::MuslX32);
626       else
627         Target.setEnvironment(llvm::Triple::GNUX32);
628     } else if (A->getOption().matches(options::OPT_m32) ||
629                A->getOption().matches(options::OPT_maix32)) {
630       AT = Target.get32BitArchVariant().getArch();
631       if (Target.getEnvironment() == llvm::Triple::GNUX32)
632         Target.setEnvironment(llvm::Triple::GNU);
633       else if (Target.getEnvironment() == llvm::Triple::MuslX32)
634         Target.setEnvironment(llvm::Triple::Musl);
635     } else if (A->getOption().matches(options::OPT_m16) &&
636                Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
637       AT = llvm::Triple::x86;
638       Target.setEnvironment(llvm::Triple::CODE16);
639     }
640 
641     if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) {
642       Target.setArch(AT);
643       if (Target.isWindowsGNUEnvironment())
644         toolchains::MinGW::fixTripleArch(D, Target, Args);
645     }
646   }
647 
648   // Handle -miamcu flag.
649   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
650     if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
651       D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
652                                                        << Target.str();
653 
654     if (A && !A->getOption().matches(options::OPT_m32))
655       D.Diag(diag::err_drv_argument_not_allowed_with)
656           << "-miamcu" << A->getBaseArg().getAsString(Args);
657 
658     Target.setArch(llvm::Triple::x86);
659     Target.setArchName("i586");
660     Target.setEnvironment(llvm::Triple::UnknownEnvironment);
661     Target.setEnvironmentName("");
662     Target.setOS(llvm::Triple::ELFIAMCU);
663     Target.setVendor(llvm::Triple::UnknownVendor);
664     Target.setVendorName("intel");
665   }
666 
667   // If target is MIPS adjust the target triple
668   // accordingly to provided ABI name.
669   if (Target.isMIPS()) {
670     if ((A = Args.getLastArg(options::OPT_mabi_EQ))) {
671       StringRef ABIName = A->getValue();
672       if (ABIName == "32") {
673         Target = Target.get32BitArchVariant();
674         if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
675             Target.getEnvironment() == llvm::Triple::GNUABIN32)
676           Target.setEnvironment(llvm::Triple::GNU);
677       } else if (ABIName == "n32") {
678         Target = Target.get64BitArchVariant();
679         if (Target.getEnvironment() == llvm::Triple::GNU ||
680             Target.getEnvironment() == llvm::Triple::GNUABI64)
681           Target.setEnvironment(llvm::Triple::GNUABIN32);
682       } else if (ABIName == "64") {
683         Target = Target.get64BitArchVariant();
684         if (Target.getEnvironment() == llvm::Triple::GNU ||
685             Target.getEnvironment() == llvm::Triple::GNUABIN32)
686           Target.setEnvironment(llvm::Triple::GNUABI64);
687       }
688     }
689   }
690 
691   // If target is RISC-V adjust the target triple according to
692   // provided architecture name
693   if (Target.isRISCV()) {
694     if (Args.hasArg(options::OPT_march_EQ) ||
695         Args.hasArg(options::OPT_mcpu_EQ)) {
696       StringRef ArchName = tools::riscv::getRISCVArch(Args, Target);
697       if (ArchName.starts_with_insensitive("rv32"))
698         Target.setArch(llvm::Triple::riscv32);
699       else if (ArchName.starts_with_insensitive("rv64"))
700         Target.setArch(llvm::Triple::riscv64);
701     }
702   }
703 
704   return Target;
705 }
706 
707 // Parse the LTO options and record the type of LTO compilation
708 // based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)?
709 // option occurs last.
710 static driver::LTOKind parseLTOMode(Driver &D, const llvm::opt::ArgList &Args,
711                                     OptSpecifier OptEq, OptSpecifier OptNeg) {
712   if (!Args.hasFlag(OptEq, OptNeg, false))
713     return LTOK_None;
714 
715   const Arg *A = Args.getLastArg(OptEq);
716   StringRef LTOName = A->getValue();
717 
718   driver::LTOKind LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
719                                 .Case("full", LTOK_Full)
720                                 .Case("thin", LTOK_Thin)
721                                 .Default(LTOK_Unknown);
722 
723   if (LTOMode == LTOK_Unknown) {
724     D.Diag(diag::err_drv_unsupported_option_argument)
725         << A->getSpelling() << A->getValue();
726     return LTOK_None;
727   }
728   return LTOMode;
729 }
730 
731 // Parse the LTO options.
732 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
733   LTOMode =
734       parseLTOMode(*this, Args, options::OPT_flto_EQ, options::OPT_fno_lto);
735 
736   OffloadLTOMode = parseLTOMode(*this, Args, options::OPT_foffload_lto_EQ,
737                                 options::OPT_fno_offload_lto);
738 
739   // Try to enable `-foffload-lto=full` if `-fopenmp-target-jit` is on.
740   if (Args.hasFlag(options::OPT_fopenmp_target_jit,
741                    options::OPT_fno_openmp_target_jit, false)) {
742     if (Arg *A = Args.getLastArg(options::OPT_foffload_lto_EQ,
743                                  options::OPT_fno_offload_lto))
744       if (OffloadLTOMode != LTOK_Full)
745         Diag(diag::err_drv_incompatible_options)
746             << A->getSpelling() << "-fopenmp-target-jit";
747     OffloadLTOMode = LTOK_Full;
748   }
749 }
750 
751 /// Compute the desired OpenMP runtime from the flags provided.
752 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
753   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
754 
755   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
756   if (A)
757     RuntimeName = A->getValue();
758 
759   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
760                 .Case("libomp", OMPRT_OMP)
761                 .Case("libgomp", OMPRT_GOMP)
762                 .Case("libiomp5", OMPRT_IOMP5)
763                 .Default(OMPRT_Unknown);
764 
765   if (RT == OMPRT_Unknown) {
766     if (A)
767       Diag(diag::err_drv_unsupported_option_argument)
768           << A->getSpelling() << A->getValue();
769     else
770       // FIXME: We could use a nicer diagnostic here.
771       Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
772   }
773 
774   return RT;
775 }
776 
777 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
778                                               InputList &Inputs) {
779 
780   //
781   // CUDA/HIP
782   //
783   // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
784   // or HIP type. However, mixed CUDA/HIP compilation is not supported.
785   bool IsCuda =
786       llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
787         return types::isCuda(I.first);
788       });
789   bool IsHIP =
790       llvm::any_of(Inputs,
791                    [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
792                      return types::isHIP(I.first);
793                    }) ||
794       C.getInputArgs().hasArg(options::OPT_hip_link);
795   if (IsCuda && IsHIP) {
796     Diag(clang::diag::err_drv_mix_cuda_hip);
797     return;
798   }
799   if (IsCuda) {
800     const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
801     const llvm::Triple &HostTriple = HostTC->getTriple();
802     auto OFK = Action::OFK_Cuda;
803     auto CudaTriple =
804         getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), HostTriple);
805     if (!CudaTriple)
806       return;
807     // Use the CUDA and host triples as the key into the ToolChains map,
808     // because the device toolchain we create depends on both.
809     auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()];
810     if (!CudaTC) {
811       CudaTC = std::make_unique<toolchains::CudaToolChain>(
812           *this, *CudaTriple, *HostTC, C.getInputArgs());
813 
814       // Emit a warning if the detected CUDA version is too new.
815       CudaInstallationDetector &CudaInstallation =
816           static_cast<toolchains::CudaToolChain &>(*CudaTC).CudaInstallation;
817       if (CudaInstallation.isValid())
818         CudaInstallation.WarnIfUnsupportedVersion();
819     }
820     C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
821   } else if (IsHIP) {
822     if (auto *OMPTargetArg =
823             C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
824       Diag(clang::diag::err_drv_unsupported_opt_for_language_mode)
825           << OMPTargetArg->getSpelling() << "HIP";
826       return;
827     }
828     const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
829     auto OFK = Action::OFK_HIP;
830     auto HIPTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
831     if (!HIPTriple)
832       return;
833     auto *HIPTC = &getOffloadingDeviceToolChain(C.getInputArgs(), *HIPTriple,
834                                                 *HostTC, OFK);
835     assert(HIPTC && "Could not create offloading device tool chain.");
836     C.addOffloadDeviceToolChain(HIPTC, OFK);
837   }
838 
839   //
840   // OpenMP
841   //
842   // We need to generate an OpenMP toolchain if the user specified targets with
843   // the -fopenmp-targets option or used --offload-arch with OpenMP enabled.
844   bool IsOpenMPOffloading =
845       C.getInputArgs().hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
846                                options::OPT_fno_openmp, false) &&
847       (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ) ||
848        C.getInputArgs().hasArg(options::OPT_offload_arch_EQ));
849   if (IsOpenMPOffloading) {
850     // We expect that -fopenmp-targets is always used in conjunction with the
851     // option -fopenmp specifying a valid runtime with offloading support, i.e.
852     // libomp or libiomp.
853     OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(C.getInputArgs());
854     if (RuntimeKind != OMPRT_OMP && RuntimeKind != OMPRT_IOMP5) {
855       Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
856       return;
857     }
858 
859     llvm::StringMap<llvm::DenseSet<StringRef>> DerivedArchs;
860     llvm::StringMap<StringRef> FoundNormalizedTriples;
861     std::multiset<StringRef> OpenMPTriples;
862 
863     // If the user specified -fopenmp-targets= we create a toolchain for each
864     // valid triple. Otherwise, if only --offload-arch= was specified we instead
865     // attempt to derive the appropriate toolchains from the arguments.
866     if (Arg *OpenMPTargets =
867             C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
868       if (OpenMPTargets && !OpenMPTargets->getNumValues()) {
869         Diag(clang::diag::warn_drv_empty_joined_argument)
870             << OpenMPTargets->getAsString(C.getInputArgs());
871         return;
872       }
873       for (StringRef T : OpenMPTargets->getValues())
874         OpenMPTriples.insert(T);
875     } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) &&
876                !IsHIP && !IsCuda) {
877       const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
878       auto AMDTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
879       auto NVPTXTriple = getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(),
880                                                       HostTC->getTriple());
881 
882       // Attempt to deduce the offloading triple from the set of architectures.
883       // We can only correctly deduce NVPTX / AMDGPU triples currently. We need
884       // to temporarily create these toolchains so that we can access tools for
885       // inferring architectures.
886       llvm::DenseSet<StringRef> Archs;
887       if (NVPTXTriple) {
888         auto TempTC = std::make_unique<toolchains::CudaToolChain>(
889             *this, *NVPTXTriple, *HostTC, C.getInputArgs());
890         for (StringRef Arch : getOffloadArchs(
891                  C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true))
892           Archs.insert(Arch);
893       }
894       if (AMDTriple) {
895         auto TempTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>(
896             *this, *AMDTriple, *HostTC, C.getInputArgs());
897         for (StringRef Arch : getOffloadArchs(
898                  C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true))
899           Archs.insert(Arch);
900       }
901       if (!AMDTriple && !NVPTXTriple) {
902         for (StringRef Arch :
903              getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr, true))
904           Archs.insert(Arch);
905       }
906 
907       for (StringRef Arch : Archs) {
908         if (NVPTXTriple && IsNVIDIAGpuArch(StringToCudaArch(
909                                getProcessorFromTargetID(*NVPTXTriple, Arch)))) {
910           DerivedArchs[NVPTXTriple->getTriple()].insert(Arch);
911         } else if (AMDTriple &&
912                    IsAMDGpuArch(StringToCudaArch(
913                        getProcessorFromTargetID(*AMDTriple, Arch)))) {
914           DerivedArchs[AMDTriple->getTriple()].insert(Arch);
915         } else {
916           Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) << Arch;
917           return;
918         }
919       }
920 
921       // If the set is empty then we failed to find a native architecture.
922       if (Archs.empty()) {
923         Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch)
924             << "native";
925         return;
926       }
927 
928       for (const auto &TripleAndArchs : DerivedArchs)
929         OpenMPTriples.insert(TripleAndArchs.first());
930     }
931 
932     for (StringRef Val : OpenMPTriples) {
933       llvm::Triple TT(ToolChain::getOpenMPTriple(Val));
934       std::string NormalizedName = TT.normalize();
935 
936       // Make sure we don't have a duplicate triple.
937       auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
938       if (Duplicate != FoundNormalizedTriples.end()) {
939         Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
940             << Val << Duplicate->second;
941         continue;
942       }
943 
944       // Store the current triple so that we can check for duplicates in the
945       // following iterations.
946       FoundNormalizedTriples[NormalizedName] = Val;
947 
948       // If the specified target is invalid, emit a diagnostic.
949       if (TT.getArch() == llvm::Triple::UnknownArch)
950         Diag(clang::diag::err_drv_invalid_omp_target) << Val;
951       else {
952         const ToolChain *TC;
953         // Device toolchains have to be selected differently. They pair host
954         // and device in their implementation.
955         if (TT.isNVPTX() || TT.isAMDGCN()) {
956           const ToolChain *HostTC =
957               C.getSingleOffloadToolChain<Action::OFK_Host>();
958           assert(HostTC && "Host toolchain should be always defined.");
959           auto &DeviceTC =
960               ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
961           if (!DeviceTC) {
962             if (TT.isNVPTX())
963               DeviceTC = std::make_unique<toolchains::CudaToolChain>(
964                   *this, TT, *HostTC, C.getInputArgs());
965             else if (TT.isAMDGCN())
966               DeviceTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>(
967                   *this, TT, *HostTC, C.getInputArgs());
968             else
969               assert(DeviceTC && "Device toolchain not defined.");
970           }
971 
972           TC = DeviceTC.get();
973         } else
974           TC = &getToolChain(C.getInputArgs(), TT);
975         C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
976         if (DerivedArchs.contains(TT.getTriple()))
977           KnownArchs[TC] = DerivedArchs[TT.getTriple()];
978       }
979     }
980   } else if (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ)) {
981     Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
982     return;
983   }
984 
985   //
986   // TODO: Add support for other offloading programming models here.
987   //
988 }
989 
990 static void appendOneArg(InputArgList &Args, const Arg *Opt,
991                          const Arg *BaseArg) {
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   unsigned Index = Args.MakeIndex(Opt->getSpelling());
996   Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Args.getArgString(Index),
997                                  Index, BaseArg);
998   Copy->getValues() = Opt->getValues();
999   if (Opt->isClaimed())
1000     Copy->claim();
1001   Copy->setOwnsValues(Opt->getOwnsValues());
1002   Opt->setOwnsValues(false);
1003   Args.append(Copy);
1004 }
1005 
1006 bool Driver::readConfigFile(StringRef FileName,
1007                             llvm::cl::ExpansionContext &ExpCtx) {
1008   // Try opening the given file.
1009   auto Status = getVFS().status(FileName);
1010   if (!Status) {
1011     Diag(diag::err_drv_cannot_open_config_file)
1012         << FileName << Status.getError().message();
1013     return true;
1014   }
1015   if (Status->getType() != llvm::sys::fs::file_type::regular_file) {
1016     Diag(diag::err_drv_cannot_open_config_file)
1017         << FileName << "not a regular file";
1018     return true;
1019   }
1020 
1021   // Try reading the given file.
1022   SmallVector<const char *, 32> NewCfgArgs;
1023   if (llvm::Error Err = ExpCtx.readConfigFile(FileName, NewCfgArgs)) {
1024     Diag(diag::err_drv_cannot_read_config_file)
1025         << FileName << toString(std::move(Err));
1026     return true;
1027   }
1028 
1029   // Read options from config file.
1030   llvm::SmallString<128> CfgFileName(FileName);
1031   llvm::sys::path::native(CfgFileName);
1032   bool ContainErrors;
1033   std::unique_ptr<InputArgList> NewOptions = std::make_unique<InputArgList>(
1034       ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
1035   if (ContainErrors)
1036     return true;
1037 
1038   // Claim all arguments that come from a configuration file so that the driver
1039   // does not warn on any that is unused.
1040   for (Arg *A : *NewOptions)
1041     A->claim();
1042 
1043   if (!CfgOptions)
1044     CfgOptions = std::move(NewOptions);
1045   else {
1046     // If this is a subsequent config file, append options to the previous one.
1047     for (auto *Opt : *NewOptions) {
1048       const Arg *BaseArg = &Opt->getBaseArg();
1049       if (BaseArg == Opt)
1050         BaseArg = nullptr;
1051       appendOneArg(*CfgOptions, Opt, BaseArg);
1052     }
1053   }
1054   ConfigFiles.push_back(std::string(CfgFileName));
1055   return false;
1056 }
1057 
1058 bool Driver::loadConfigFiles() {
1059   llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(),
1060                                     llvm::cl::tokenizeConfigFile);
1061   ExpCtx.setVFS(&getVFS());
1062 
1063   // Process options that change search path for config files.
1064   if (CLOptions) {
1065     if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
1066       SmallString<128> CfgDir;
1067       CfgDir.append(
1068           CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
1069       if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
1070         SystemConfigDir.clear();
1071       else
1072         SystemConfigDir = static_cast<std::string>(CfgDir);
1073     }
1074     if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
1075       SmallString<128> CfgDir;
1076       llvm::sys::fs::expand_tilde(
1077           CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ), CfgDir);
1078       if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
1079         UserConfigDir.clear();
1080       else
1081         UserConfigDir = static_cast<std::string>(CfgDir);
1082     }
1083   }
1084 
1085   // Prepare list of directories where config file is searched for.
1086   StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir};
1087   ExpCtx.setSearchDirs(CfgFileSearchDirs);
1088 
1089   // First try to load configuration from the default files, return on error.
1090   if (loadDefaultConfigFiles(ExpCtx))
1091     return true;
1092 
1093   // Then load configuration files specified explicitly.
1094   SmallString<128> CfgFilePath;
1095   if (CLOptions) {
1096     for (auto CfgFileName : CLOptions->getAllArgValues(options::OPT_config)) {
1097       // If argument contains directory separator, treat it as a path to
1098       // configuration file.
1099       if (llvm::sys::path::has_parent_path(CfgFileName)) {
1100         CfgFilePath.assign(CfgFileName);
1101         if (llvm::sys::path::is_relative(CfgFilePath)) {
1102           if (getVFS().makeAbsolute(CfgFilePath)) {
1103             Diag(diag::err_drv_cannot_open_config_file)
1104                 << CfgFilePath << "cannot get absolute path";
1105             return true;
1106           }
1107         }
1108       } else if (!ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) {
1109         // Report an error that the config file could not be found.
1110         Diag(diag::err_drv_config_file_not_found) << CfgFileName;
1111         for (const StringRef &SearchDir : CfgFileSearchDirs)
1112           if (!SearchDir.empty())
1113             Diag(diag::note_drv_config_file_searched_in) << SearchDir;
1114         return true;
1115       }
1116 
1117       // Try to read the config file, return on error.
1118       if (readConfigFile(CfgFilePath, ExpCtx))
1119         return true;
1120     }
1121   }
1122 
1123   // No error occurred.
1124   return false;
1125 }
1126 
1127 bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) {
1128   // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty
1129   // value.
1130   if (const char *NoConfigEnv = ::getenv("CLANG_NO_DEFAULT_CONFIG")) {
1131     if (*NoConfigEnv)
1132       return false;
1133   }
1134   if (CLOptions && CLOptions->hasArg(options::OPT_no_default_config))
1135     return false;
1136 
1137   std::string RealMode = getExecutableForDriverMode(Mode);
1138   std::string Triple;
1139 
1140   // If name prefix is present, no --target= override was passed via CLOptions
1141   // and the name prefix is not a valid triple, force it for backwards
1142   // compatibility.
1143   if (!ClangNameParts.TargetPrefix.empty() &&
1144       computeTargetTriple(*this, "/invalid/", *CLOptions).str() ==
1145           "/invalid/") {
1146     llvm::Triple PrefixTriple{ClangNameParts.TargetPrefix};
1147     if (PrefixTriple.getArch() == llvm::Triple::UnknownArch ||
1148         PrefixTriple.isOSUnknown())
1149       Triple = PrefixTriple.str();
1150   }
1151 
1152   // Otherwise, use the real triple as used by the driver.
1153   if (Triple.empty()) {
1154     llvm::Triple RealTriple =
1155         computeTargetTriple(*this, TargetTriple, *CLOptions);
1156     Triple = RealTriple.str();
1157     assert(!Triple.empty());
1158   }
1159 
1160   // Search for config files in the following order:
1161   // 1. <triple>-<mode>.cfg using real driver mode
1162   //    (e.g. i386-pc-linux-gnu-clang++.cfg).
1163   // 2. <triple>-<mode>.cfg using executable suffix
1164   //    (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++).
1165   // 3. <triple>.cfg + <mode>.cfg using real driver mode
1166   //    (e.g. i386-pc-linux-gnu.cfg + clang++.cfg).
1167   // 4. <triple>.cfg + <mode>.cfg using executable suffix
1168   //    (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++).
1169 
1170   // Try loading <triple>-<mode>.cfg, and return if we find a match.
1171   SmallString<128> CfgFilePath;
1172   std::string CfgFileName = Triple + '-' + RealMode + ".cfg";
1173   if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1174     return readConfigFile(CfgFilePath, ExpCtx);
1175 
1176   bool TryModeSuffix = !ClangNameParts.ModeSuffix.empty() &&
1177                        ClangNameParts.ModeSuffix != RealMode;
1178   if (TryModeSuffix) {
1179     CfgFileName = Triple + '-' + ClangNameParts.ModeSuffix + ".cfg";
1180     if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1181       return readConfigFile(CfgFilePath, ExpCtx);
1182   }
1183 
1184   // Try loading <mode>.cfg, and return if loading failed.  If a matching file
1185   // was not found, still proceed on to try <triple>.cfg.
1186   CfgFileName = RealMode + ".cfg";
1187   if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) {
1188     if (readConfigFile(CfgFilePath, ExpCtx))
1189       return true;
1190   } else if (TryModeSuffix) {
1191     CfgFileName = ClangNameParts.ModeSuffix + ".cfg";
1192     if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath) &&
1193         readConfigFile(CfgFilePath, ExpCtx))
1194       return true;
1195   }
1196 
1197   // Try loading <triple>.cfg and return if we find a match.
1198   CfgFileName = Triple + ".cfg";
1199   if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1200     return readConfigFile(CfgFilePath, ExpCtx);
1201 
1202   // If we were unable to find a config file deduced from executable name,
1203   // that is not an error.
1204   return false;
1205 }
1206 
1207 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
1208   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
1209 
1210   // FIXME: Handle environment options which affect driver behavior, somewhere
1211   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
1212 
1213   // We look for the driver mode option early, because the mode can affect
1214   // how other options are parsed.
1215 
1216   auto DriverMode = getDriverMode(ClangExecutable, ArgList.slice(1));
1217   if (!DriverMode.empty())
1218     setDriverMode(DriverMode);
1219 
1220   // FIXME: What are we going to do with -V and -b?
1221 
1222   // Arguments specified in command line.
1223   bool ContainsError;
1224   CLOptions = std::make_unique<InputArgList>(
1225       ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
1226 
1227   // Try parsing configuration file.
1228   if (!ContainsError)
1229     ContainsError = loadConfigFiles();
1230   bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
1231 
1232   // All arguments, from both config file and command line.
1233   InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
1234                                               : std::move(*CLOptions));
1235 
1236   if (HasConfigFile)
1237     for (auto *Opt : *CLOptions) {
1238       if (Opt->getOption().matches(options::OPT_config))
1239         continue;
1240       const Arg *BaseArg = &Opt->getBaseArg();
1241       if (BaseArg == Opt)
1242         BaseArg = nullptr;
1243       appendOneArg(Args, Opt, BaseArg);
1244     }
1245 
1246   // In CL mode, look for any pass-through arguments
1247   if (IsCLMode() && !ContainsError) {
1248     SmallVector<const char *, 16> CLModePassThroughArgList;
1249     for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1250       A->claim();
1251       CLModePassThroughArgList.push_back(A->getValue());
1252     }
1253 
1254     if (!CLModePassThroughArgList.empty()) {
1255       // Parse any pass through args using default clang processing rather
1256       // than clang-cl processing.
1257       auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1258           ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1259 
1260       if (!ContainsError)
1261         for (auto *Opt : *CLModePassThroughOptions) {
1262           appendOneArg(Args, Opt, nullptr);
1263         }
1264     }
1265   }
1266 
1267   // Check for working directory option before accessing any files
1268   if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1269     if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1270       Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1271 
1272   // FIXME: This stuff needs to go into the Compilation, not the driver.
1273   bool CCCPrintPhases;
1274 
1275   // -canonical-prefixes, -no-canonical-prefixes are used very early in main.
1276   Args.ClaimAllArgs(options::OPT_canonical_prefixes);
1277   Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1278 
1279   // f(no-)integated-cc1 is also used very early in main.
1280   Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1281   Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1282 
1283   // Ignore -pipe.
1284   Args.ClaimAllArgs(options::OPT_pipe);
1285 
1286   // Extract -ccc args.
1287   //
1288   // FIXME: We need to figure out where this behavior should live. Most of it
1289   // should be outside in the client; the parts that aren't should have proper
1290   // options, either by introducing new ones or by overloading gcc ones like -V
1291   // or -b.
1292   CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1293   CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1294   if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1295     CCCGenericGCCName = A->getValue();
1296 
1297   // Process -fproc-stat-report options.
1298   if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) {
1299     CCPrintProcessStats = true;
1300     CCPrintStatReportFilename = A->getValue();
1301   }
1302   if (Args.hasArg(options::OPT_fproc_stat_report))
1303     CCPrintProcessStats = true;
1304 
1305   // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1306   // and getToolChain is const.
1307   if (IsCLMode()) {
1308     // clang-cl targets MSVC-style Win32.
1309     llvm::Triple T(TargetTriple);
1310     T.setOS(llvm::Triple::Win32);
1311     T.setVendor(llvm::Triple::PC);
1312     T.setEnvironment(llvm::Triple::MSVC);
1313     T.setObjectFormat(llvm::Triple::COFF);
1314     if (Args.hasArg(options::OPT__SLASH_arm64EC))
1315       T.setArch(llvm::Triple::aarch64, llvm::Triple::AArch64SubArch_arm64ec);
1316     TargetTriple = T.str();
1317   } else if (IsDXCMode()) {
1318     // Build TargetTriple from target_profile option for clang-dxc.
1319     if (const Arg *A = Args.getLastArg(options::OPT_target_profile)) {
1320       StringRef TargetProfile = A->getValue();
1321       if (auto Triple =
1322               toolchains::HLSLToolChain::parseTargetProfile(TargetProfile))
1323         TargetTriple = *Triple;
1324       else
1325         Diag(diag::err_drv_invalid_directx_shader_module) << TargetProfile;
1326 
1327       A->claim();
1328     } else {
1329       Diag(diag::err_drv_dxc_missing_target_profile);
1330     }
1331   }
1332 
1333   if (const Arg *A = Args.getLastArg(options::OPT_target))
1334     TargetTriple = A->getValue();
1335   if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1336     Dir = InstalledDir = A->getValue();
1337   for (const Arg *A : Args.filtered(options::OPT_B)) {
1338     A->claim();
1339     PrefixDirs.push_back(A->getValue(0));
1340   }
1341   if (std::optional<std::string> CompilerPathValue =
1342           llvm::sys::Process::GetEnv("COMPILER_PATH")) {
1343     StringRef CompilerPath = *CompilerPathValue;
1344     while (!CompilerPath.empty()) {
1345       std::pair<StringRef, StringRef> Split =
1346           CompilerPath.split(llvm::sys::EnvPathSeparator);
1347       PrefixDirs.push_back(std::string(Split.first));
1348       CompilerPath = Split.second;
1349     }
1350   }
1351   if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1352     SysRoot = A->getValue();
1353   if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1354     DyldPrefix = A->getValue();
1355 
1356   if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1357     ResourceDir = A->getValue();
1358 
1359   if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1360     SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1361                     .Case("cwd", SaveTempsCwd)
1362                     .Case("obj", SaveTempsObj)
1363                     .Default(SaveTempsCwd);
1364   }
1365 
1366   if (const Arg *A = Args.getLastArg(options::OPT_offload_host_only,
1367                                      options::OPT_offload_device_only,
1368                                      options::OPT_offload_host_device)) {
1369     if (A->getOption().matches(options::OPT_offload_host_only))
1370       Offload = OffloadHost;
1371     else if (A->getOption().matches(options::OPT_offload_device_only))
1372       Offload = OffloadDevice;
1373     else
1374       Offload = OffloadHostDevice;
1375   }
1376 
1377   setLTOMode(Args);
1378 
1379   // Process -fembed-bitcode= flags.
1380   if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1381     StringRef Name = A->getValue();
1382     unsigned Model = llvm::StringSwitch<unsigned>(Name)
1383         .Case("off", EmbedNone)
1384         .Case("all", EmbedBitcode)
1385         .Case("bitcode", EmbedBitcode)
1386         .Case("marker", EmbedMarker)
1387         .Default(~0U);
1388     if (Model == ~0U) {
1389       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1390                                                 << Name;
1391     } else
1392       BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1393   }
1394 
1395   // Remove existing compilation database so that each job can append to it.
1396   if (Arg *A = Args.getLastArg(options::OPT_MJ))
1397     llvm::sys::fs::remove(A->getValue());
1398 
1399   // Setting up the jobs for some precompile cases depends on whether we are
1400   // treating them as PCH, implicit modules or C++20 ones.
1401   // TODO: inferring the mode like this seems fragile (it meets the objective
1402   // of not requiring anything new for operation, however).
1403   const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
1404   ModulesModeCXX20 =
1405       !Args.hasArg(options::OPT_fmodules) && Std &&
1406       (Std->containsValue("c++20") || Std->containsValue("c++2a") ||
1407        Std->containsValue("c++23") || Std->containsValue("c++2b") ||
1408        Std->containsValue("c++26") || Std->containsValue("c++2c") ||
1409        Std->containsValue("c++latest"));
1410 
1411   // Process -fmodule-header{=} flags.
1412   if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ,
1413                                options::OPT_fmodule_header)) {
1414     // These flags force C++20 handling of headers.
1415     ModulesModeCXX20 = true;
1416     if (A->getOption().matches(options::OPT_fmodule_header))
1417       CXX20HeaderType = HeaderMode_Default;
1418     else {
1419       StringRef ArgName = A->getValue();
1420       unsigned Kind = llvm::StringSwitch<unsigned>(ArgName)
1421                           .Case("user", HeaderMode_User)
1422                           .Case("system", HeaderMode_System)
1423                           .Default(~0U);
1424       if (Kind == ~0U) {
1425         Diags.Report(diag::err_drv_invalid_value)
1426             << A->getAsString(Args) << ArgName;
1427       } else
1428         CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind);
1429     }
1430   }
1431 
1432   std::unique_ptr<llvm::opt::InputArgList> UArgs =
1433       std::make_unique<InputArgList>(std::move(Args));
1434 
1435   // Perform the default argument translations.
1436   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1437 
1438   // Owned by the host.
1439   const ToolChain &TC = getToolChain(
1440       *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1441 
1442   // Report warning when arm64EC option is overridden by specified target
1443   if ((TC.getTriple().getArch() != llvm::Triple::aarch64 ||
1444        TC.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec) &&
1445       UArgs->hasArg(options::OPT__SLASH_arm64EC)) {
1446     getDiags().Report(clang::diag::warn_target_override_arm64ec)
1447         << TC.getTriple().str();
1448   }
1449 
1450   // A common user mistake is specifying a target of aarch64-none-eabi or
1451   // arm-none-elf whereas the correct names are aarch64-none-elf &
1452   // arm-none-eabi. Detect these cases and issue a warning.
1453   if (TC.getTriple().getOS() == llvm::Triple::UnknownOS &&
1454       TC.getTriple().getVendor() == llvm::Triple::UnknownVendor) {
1455     switch (TC.getTriple().getArch()) {
1456     case llvm::Triple::arm:
1457     case llvm::Triple::armeb:
1458     case llvm::Triple::thumb:
1459     case llvm::Triple::thumbeb:
1460       if (TC.getTriple().getEnvironmentName() == "elf") {
1461         Diag(diag::warn_target_unrecognized_env)
1462             << TargetTriple
1463             << (TC.getTriple().getArchName().str() + "-none-eabi");
1464       }
1465       break;
1466     case llvm::Triple::aarch64:
1467     case llvm::Triple::aarch64_be:
1468     case llvm::Triple::aarch64_32:
1469       if (TC.getTriple().getEnvironmentName().startswith("eabi")) {
1470         Diag(diag::warn_target_unrecognized_env)
1471             << TargetTriple
1472             << (TC.getTriple().getArchName().str() + "-none-elf");
1473       }
1474       break;
1475     default:
1476       break;
1477     }
1478   }
1479 
1480   // The compilation takes ownership of Args.
1481   Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1482                                    ContainsError);
1483 
1484   if (!HandleImmediateArgs(*C))
1485     return C;
1486 
1487   // Construct the list of inputs.
1488   InputList Inputs;
1489   BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1490 
1491   // Populate the tool chains for the offloading devices, if any.
1492   CreateOffloadingDeviceToolChains(*C, Inputs);
1493 
1494   // Construct the list of abstract actions to perform for this compilation. On
1495   // MachO targets this uses the driver-driver and universal actions.
1496   if (TC.getTriple().isOSBinFormatMachO())
1497     BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1498   else
1499     BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1500 
1501   if (CCCPrintPhases) {
1502     PrintActions(*C);
1503     return C;
1504   }
1505 
1506   BuildJobs(*C);
1507 
1508   return C;
1509 }
1510 
1511 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1512   llvm::opt::ArgStringList ASL;
1513   for (const auto *A : Args) {
1514     // Use user's original spelling of flags. For example, use
1515     // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user
1516     // wrote the former.
1517     while (A->getAlias())
1518       A = A->getAlias();
1519     A->render(Args, ASL);
1520   }
1521 
1522   for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1523     if (I != ASL.begin())
1524       OS << ' ';
1525     llvm::sys::printArg(OS, *I, true);
1526   }
1527   OS << '\n';
1528 }
1529 
1530 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1531                                     SmallString<128> &CrashDiagDir) {
1532   using namespace llvm::sys;
1533   assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1534          "Only knows about .crash files on Darwin");
1535 
1536   // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1537   // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1538   // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1539   path::home_directory(CrashDiagDir);
1540   if (CrashDiagDir.startswith("/var/root"))
1541     CrashDiagDir = "/";
1542   path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1543   int PID =
1544 #if LLVM_ON_UNIX
1545       getpid();
1546 #else
1547       0;
1548 #endif
1549   std::error_code EC;
1550   fs::file_status FileStatus;
1551   TimePoint<> LastAccessTime;
1552   SmallString<128> CrashFilePath;
1553   // Lookup the .crash files and get the one generated by a subprocess spawned
1554   // by this driver invocation.
1555   for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1556        File != FileEnd && !EC; File.increment(EC)) {
1557     StringRef FileName = path::filename(File->path());
1558     if (!FileName.startswith(Name))
1559       continue;
1560     if (fs::status(File->path(), FileStatus))
1561       continue;
1562     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1563         llvm::MemoryBuffer::getFile(File->path());
1564     if (!CrashFile)
1565       continue;
1566     // The first line should start with "Process:", otherwise this isn't a real
1567     // .crash file.
1568     StringRef Data = CrashFile.get()->getBuffer();
1569     if (!Data.startswith("Process:"))
1570       continue;
1571     // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1572     size_t ParentProcPos = Data.find("Parent Process:");
1573     if (ParentProcPos == StringRef::npos)
1574       continue;
1575     size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1576     if (LineEnd == StringRef::npos)
1577       continue;
1578     StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1579     int OpenBracket = -1, CloseBracket = -1;
1580     for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1581       if (ParentProcess[i] == '[')
1582         OpenBracket = i;
1583       if (ParentProcess[i] == ']')
1584         CloseBracket = i;
1585     }
1586     // Extract the parent process PID from the .crash file and check whether
1587     // it matches this driver invocation pid.
1588     int CrashPID;
1589     if (OpenBracket < 0 || CloseBracket < 0 ||
1590         ParentProcess.slice(OpenBracket + 1, CloseBracket)
1591             .getAsInteger(10, CrashPID) || CrashPID != PID) {
1592       continue;
1593     }
1594 
1595     // Found a .crash file matching the driver pid. To avoid getting an older
1596     // and misleading crash file, continue looking for the most recent.
1597     // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1598     // multiple crashes poiting to the same parent process. Since the driver
1599     // does not collect pid information for the dispatched invocation there's
1600     // currently no way to distinguish among them.
1601     const auto FileAccessTime = FileStatus.getLastModificationTime();
1602     if (FileAccessTime > LastAccessTime) {
1603       CrashFilePath.assign(File->path());
1604       LastAccessTime = FileAccessTime;
1605     }
1606   }
1607 
1608   // If found, copy it over to the location of other reproducer files.
1609   if (!CrashFilePath.empty()) {
1610     EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1611     if (EC)
1612       return false;
1613     return true;
1614   }
1615 
1616   return false;
1617 }
1618 
1619 static const char BugReporMsg[] =
1620     "\n********************\n\n"
1621     "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1622     "Preprocessed source(s) and associated run script(s) are located at:";
1623 
1624 // When clang crashes, produce diagnostic information including the fully
1625 // preprocessed source file(s).  Request that the developer attach the
1626 // diagnostic information to a bug report.
1627 void Driver::generateCompilationDiagnostics(
1628     Compilation &C, const Command &FailingCommand,
1629     StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1630   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1631     return;
1632 
1633   unsigned Level = 1;
1634   if (Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_EQ)) {
1635     Level = llvm::StringSwitch<unsigned>(A->getValue())
1636                 .Case("off", 0)
1637                 .Case("compiler", 1)
1638                 .Case("all", 2)
1639                 .Default(1);
1640   }
1641   if (!Level)
1642     return;
1643 
1644   // Don't try to generate diagnostics for dsymutil jobs.
1645   if (FailingCommand.getCreator().isDsymutilJob())
1646     return;
1647 
1648   bool IsLLD = false;
1649   ArgStringList SavedTemps;
1650   if (FailingCommand.getCreator().isLinkJob()) {
1651     C.getDefaultToolChain().GetLinkerPath(&IsLLD);
1652     if (!IsLLD || Level < 2)
1653       return;
1654 
1655     // If lld crashed, we will re-run the same command with the input it used
1656     // to have. In that case we should not remove temp files in
1657     // initCompilationForDiagnostics yet. They will be added back and removed
1658     // later.
1659     SavedTemps = std::move(C.getTempFiles());
1660     assert(!C.getTempFiles().size());
1661   }
1662 
1663   // Print the version of the compiler.
1664   PrintVersion(C, llvm::errs());
1665 
1666   // Suppress driver output and emit preprocessor output to temp file.
1667   CCGenDiagnostics = true;
1668 
1669   // Save the original job command(s).
1670   Command Cmd = FailingCommand;
1671 
1672   // Keep track of whether we produce any errors while trying to produce
1673   // preprocessed sources.
1674   DiagnosticErrorTrap Trap(Diags);
1675 
1676   // Suppress tool output.
1677   C.initCompilationForDiagnostics();
1678 
1679   // If lld failed, rerun it again with --reproduce.
1680   if (IsLLD) {
1681     const char *TmpName = CreateTempFile(C, "linker-crash", "tar");
1682     Command NewLLDInvocation = Cmd;
1683     llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments();
1684     StringRef ReproduceOption =
1685         C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment()
1686             ? "/reproduce:"
1687             : "--reproduce=";
1688     ArgList.push_back(Saver.save(Twine(ReproduceOption) + TmpName).data());
1689     NewLLDInvocation.replaceArguments(std::move(ArgList));
1690 
1691     // Redirect stdout/stderr to /dev/null.
1692     NewLLDInvocation.Execute({std::nullopt, {""}, {""}}, nullptr, nullptr);
1693     Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg;
1694     Diag(clang::diag::note_drv_command_failed_diag_msg) << TmpName;
1695     Diag(clang::diag::note_drv_command_failed_diag_msg)
1696         << "\n\n********************";
1697     if (Report)
1698       Report->TemporaryFiles.push_back(TmpName);
1699     return;
1700   }
1701 
1702   // Construct the list of inputs.
1703   InputList Inputs;
1704   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1705 
1706   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1707     bool IgnoreInput = false;
1708 
1709     // Ignore input from stdin or any inputs that cannot be preprocessed.
1710     // Check type first as not all linker inputs have a value.
1711     if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1712       IgnoreInput = true;
1713     } else if (!strcmp(it->second->getValue(), "-")) {
1714       Diag(clang::diag::note_drv_command_failed_diag_msg)
1715           << "Error generating preprocessed source(s) - "
1716              "ignoring input from stdin.";
1717       IgnoreInput = true;
1718     }
1719 
1720     if (IgnoreInput) {
1721       it = Inputs.erase(it);
1722       ie = Inputs.end();
1723     } else {
1724       ++it;
1725     }
1726   }
1727 
1728   if (Inputs.empty()) {
1729     Diag(clang::diag::note_drv_command_failed_diag_msg)
1730         << "Error generating preprocessed source(s) - "
1731            "no preprocessable inputs.";
1732     return;
1733   }
1734 
1735   // Don't attempt to generate preprocessed files if multiple -arch options are
1736   // used, unless they're all duplicates.
1737   llvm::StringSet<> ArchNames;
1738   for (const Arg *A : C.getArgs()) {
1739     if (A->getOption().matches(options::OPT_arch)) {
1740       StringRef ArchName = A->getValue();
1741       ArchNames.insert(ArchName);
1742     }
1743   }
1744   if (ArchNames.size() > 1) {
1745     Diag(clang::diag::note_drv_command_failed_diag_msg)
1746         << "Error generating preprocessed source(s) - cannot generate "
1747            "preprocessed source with multiple -arch options.";
1748     return;
1749   }
1750 
1751   // Construct the list of abstract actions to perform for this compilation. On
1752   // Darwin OSes this uses the driver-driver and builds universal actions.
1753   const ToolChain &TC = C.getDefaultToolChain();
1754   if (TC.getTriple().isOSBinFormatMachO())
1755     BuildUniversalActions(C, TC, Inputs);
1756   else
1757     BuildActions(C, C.getArgs(), Inputs, C.getActions());
1758 
1759   BuildJobs(C);
1760 
1761   // If there were errors building the compilation, quit now.
1762   if (Trap.hasErrorOccurred()) {
1763     Diag(clang::diag::note_drv_command_failed_diag_msg)
1764         << "Error generating preprocessed source(s).";
1765     return;
1766   }
1767 
1768   // Generate preprocessed output.
1769   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1770   C.ExecuteJobs(C.getJobs(), FailingCommands);
1771 
1772   // If any of the preprocessing commands failed, clean up and exit.
1773   if (!FailingCommands.empty()) {
1774     Diag(clang::diag::note_drv_command_failed_diag_msg)
1775         << "Error generating preprocessed source(s).";
1776     return;
1777   }
1778 
1779   const ArgStringList &TempFiles = C.getTempFiles();
1780   if (TempFiles.empty()) {
1781     Diag(clang::diag::note_drv_command_failed_diag_msg)
1782         << "Error generating preprocessed source(s).";
1783     return;
1784   }
1785 
1786   Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg;
1787 
1788   SmallString<128> VFS;
1789   SmallString<128> ReproCrashFilename;
1790   for (const char *TempFile : TempFiles) {
1791     Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1792     if (Report)
1793       Report->TemporaryFiles.push_back(TempFile);
1794     if (ReproCrashFilename.empty()) {
1795       ReproCrashFilename = TempFile;
1796       llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1797     }
1798     if (StringRef(TempFile).endswith(".cache")) {
1799       // In some cases (modules) we'll dump extra data to help with reproducing
1800       // the crash into a directory next to the output.
1801       VFS = llvm::sys::path::filename(TempFile);
1802       llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1803     }
1804   }
1805 
1806   for (const char *TempFile : SavedTemps)
1807     C.addTempFile(TempFile);
1808 
1809   // Assume associated files are based off of the first temporary file.
1810   CrashReportInfo CrashInfo(TempFiles[0], VFS);
1811 
1812   llvm::SmallString<128> Script(CrashInfo.Filename);
1813   llvm::sys::path::replace_extension(Script, "sh");
1814   std::error_code EC;
1815   llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew,
1816                                 llvm::sys::fs::FA_Write,
1817                                 llvm::sys::fs::OF_Text);
1818   if (EC) {
1819     Diag(clang::diag::note_drv_command_failed_diag_msg)
1820         << "Error generating run script: " << Script << " " << EC.message();
1821   } else {
1822     ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1823              << "# Driver args: ";
1824     printArgList(ScriptOS, C.getInputArgs());
1825     ScriptOS << "# Original command: ";
1826     Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1827     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1828     if (!AdditionalInformation.empty())
1829       ScriptOS << "\n# Additional information: " << AdditionalInformation
1830                << "\n";
1831     if (Report)
1832       Report->TemporaryFiles.push_back(std::string(Script.str()));
1833     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1834   }
1835 
1836   // On darwin, provide information about the .crash diagnostic report.
1837   if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1838     SmallString<128> CrashDiagDir;
1839     if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1840       Diag(clang::diag::note_drv_command_failed_diag_msg)
1841           << ReproCrashFilename.str();
1842     } else { // Suggest a directory for the user to look for .crash files.
1843       llvm::sys::path::append(CrashDiagDir, Name);
1844       CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1845       Diag(clang::diag::note_drv_command_failed_diag_msg)
1846           << "Crash backtrace is located in";
1847       Diag(clang::diag::note_drv_command_failed_diag_msg)
1848           << CrashDiagDir.str();
1849       Diag(clang::diag::note_drv_command_failed_diag_msg)
1850           << "(choose the .crash file that corresponds to your crash)";
1851     }
1852   }
1853 
1854   Diag(clang::diag::note_drv_command_failed_diag_msg)
1855       << "\n\n********************";
1856 }
1857 
1858 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1859   // Since commandLineFitsWithinSystemLimits() may underestimate system's
1860   // capacity if the tool does not support response files, there is a chance/
1861   // that things will just work without a response file, so we silently just
1862   // skip it.
1863   if (Cmd.getResponseFileSupport().ResponseKind ==
1864           ResponseFileSupport::RF_None ||
1865       llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1866                                                    Cmd.getArguments()))
1867     return;
1868 
1869   std::string TmpName = GetTemporaryPath("response", "txt");
1870   Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1871 }
1872 
1873 int Driver::ExecuteCompilation(
1874     Compilation &C,
1875     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1876   if (C.getArgs().hasArg(options::OPT_fdriver_only)) {
1877     if (C.getArgs().hasArg(options::OPT_v))
1878       C.getJobs().Print(llvm::errs(), "\n", true);
1879 
1880     C.ExecuteJobs(C.getJobs(), FailingCommands, /*LogOnly=*/true);
1881 
1882     // If there were errors building the compilation, quit now.
1883     if (!FailingCommands.empty() || Diags.hasErrorOccurred())
1884       return 1;
1885 
1886     return 0;
1887   }
1888 
1889   // Just print if -### was present.
1890   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1891     C.getJobs().Print(llvm::errs(), "\n", true);
1892     return 0;
1893   }
1894 
1895   // If there were errors building the compilation, quit now.
1896   if (Diags.hasErrorOccurred())
1897     return 1;
1898 
1899   // Set up response file names for each command, if necessary.
1900   for (auto &Job : C.getJobs())
1901     setUpResponseFiles(C, Job);
1902 
1903   C.ExecuteJobs(C.getJobs(), FailingCommands);
1904 
1905   // If the command succeeded, we are done.
1906   if (FailingCommands.empty())
1907     return 0;
1908 
1909   // Otherwise, remove result files and print extra information about abnormal
1910   // failures.
1911   int Res = 0;
1912   for (const auto &CmdPair : FailingCommands) {
1913     int CommandRes = CmdPair.first;
1914     const Command *FailingCommand = CmdPair.second;
1915 
1916     // Remove result files if we're not saving temps.
1917     if (!isSaveTempsEnabled()) {
1918       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1919       C.CleanupFileMap(C.getResultFiles(), JA, true);
1920 
1921       // Failure result files are valid unless we crashed.
1922       if (CommandRes < 0)
1923         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1924     }
1925 
1926     // llvm/lib/Support/*/Signals.inc will exit with a special return code
1927     // for SIGPIPE. Do not print diagnostics for this case.
1928     if (CommandRes == EX_IOERR) {
1929       Res = CommandRes;
1930       continue;
1931     }
1932 
1933     // Print extra information about abnormal failures, if possible.
1934     //
1935     // This is ad-hoc, but we don't want to be excessively noisy. If the result
1936     // status was 1, assume the command failed normally. In particular, if it
1937     // was the compiler then assume it gave a reasonable error code. Failures
1938     // in other tools are less common, and they generally have worse
1939     // diagnostics, so always print the diagnostic there.
1940     const Tool &FailingTool = FailingCommand->getCreator();
1941 
1942     if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1943       // FIXME: See FIXME above regarding result code interpretation.
1944       if (CommandRes < 0)
1945         Diag(clang::diag::err_drv_command_signalled)
1946             << FailingTool.getShortName();
1947       else
1948         Diag(clang::diag::err_drv_command_failed)
1949             << FailingTool.getShortName() << CommandRes;
1950     }
1951   }
1952   return Res;
1953 }
1954 
1955 void Driver::PrintHelp(bool ShowHidden) const {
1956   unsigned IncludedFlagsBitmask;
1957   unsigned ExcludedFlagsBitmask;
1958   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1959       getIncludeExcludeOptionFlagMasks(IsCLMode());
1960 
1961   ExcludedFlagsBitmask |= options::NoDriverOption;
1962   if (!ShowHidden)
1963     ExcludedFlagsBitmask |= HelpHidden;
1964 
1965   if (IsFlangMode())
1966     IncludedFlagsBitmask |= options::FlangOption;
1967   else
1968     ExcludedFlagsBitmask |= options::FlangOnlyOption;
1969 
1970   std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1971   getOpts().printHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1972                       IncludedFlagsBitmask, ExcludedFlagsBitmask,
1973                       /*ShowAllAliases=*/false);
1974 }
1975 
1976 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1977   if (IsFlangMode()) {
1978     OS << getClangToolFullVersion("flang-new") << '\n';
1979   } else {
1980     // FIXME: The following handlers should use a callback mechanism, we don't
1981     // know what the client would like to do.
1982     OS << getClangFullVersion() << '\n';
1983   }
1984   const ToolChain &TC = C.getDefaultToolChain();
1985   OS << "Target: " << TC.getTripleString() << '\n';
1986 
1987   // Print the threading model.
1988   if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1989     // Don't print if the ToolChain would have barfed on it already
1990     if (TC.isThreadModelSupported(A->getValue()))
1991       OS << "Thread model: " << A->getValue();
1992   } else
1993     OS << "Thread model: " << TC.getThreadModel();
1994   OS << '\n';
1995 
1996   // Print out the install directory.
1997   OS << "InstalledDir: " << InstalledDir << '\n';
1998 
1999   // If configuration files were used, print their paths.
2000   for (auto ConfigFile : ConfigFiles)
2001     OS << "Configuration file: " << ConfigFile << '\n';
2002 }
2003 
2004 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
2005 /// option.
2006 static void PrintDiagnosticCategories(raw_ostream &OS) {
2007   // Skip the empty category.
2008   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
2009        ++i)
2010     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
2011 }
2012 
2013 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
2014   if (PassedFlags == "")
2015     return;
2016   // Print out all options that start with a given argument. This is used for
2017   // shell autocompletion.
2018   std::vector<std::string> SuggestedCompletions;
2019   std::vector<std::string> Flags;
2020 
2021   unsigned int DisableFlags =
2022       options::NoDriverOption | options::Unsupported | options::Ignored;
2023 
2024   // Make sure that Flang-only options don't pollute the Clang output
2025   // TODO: Make sure that Clang-only options don't pollute Flang output
2026   if (!IsFlangMode())
2027     DisableFlags |= options::FlangOnlyOption;
2028 
2029   // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
2030   // because the latter indicates that the user put space before pushing tab
2031   // which should end up in a file completion.
2032   const bool HasSpace = PassedFlags.endswith(",");
2033 
2034   // Parse PassedFlags by "," as all the command-line flags are passed to this
2035   // function separated by ","
2036   StringRef TargetFlags = PassedFlags;
2037   while (TargetFlags != "") {
2038     StringRef CurFlag;
2039     std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
2040     Flags.push_back(std::string(CurFlag));
2041   }
2042 
2043   // We want to show cc1-only options only when clang is invoked with -cc1 or
2044   // -Xclang.
2045   if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
2046     DisableFlags &= ~options::NoDriverOption;
2047 
2048   const llvm::opt::OptTable &Opts = getOpts();
2049   StringRef Cur;
2050   Cur = Flags.at(Flags.size() - 1);
2051   StringRef Prev;
2052   if (Flags.size() >= 2) {
2053     Prev = Flags.at(Flags.size() - 2);
2054     SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
2055   }
2056 
2057   if (SuggestedCompletions.empty())
2058     SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
2059 
2060   // If Flags were empty, it means the user typed `clang [tab]` where we should
2061   // list all possible flags. If there was no value completion and the user
2062   // pressed tab after a space, we should fall back to a file completion.
2063   // We're printing a newline to be consistent with what we print at the end of
2064   // this function.
2065   if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
2066     llvm::outs() << '\n';
2067     return;
2068   }
2069 
2070   // When flag ends with '=' and there was no value completion, return empty
2071   // string and fall back to the file autocompletion.
2072   if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
2073     // If the flag is in the form of "--autocomplete=-foo",
2074     // we were requested to print out all option names that start with "-foo".
2075     // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
2076     SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
2077 
2078     // We have to query the -W flags manually as they're not in the OptTable.
2079     // TODO: Find a good way to add them to OptTable instead and them remove
2080     // this code.
2081     for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
2082       if (S.startswith(Cur))
2083         SuggestedCompletions.push_back(std::string(S));
2084   }
2085 
2086   // Sort the autocomplete candidates so that shells print them out in a
2087   // deterministic order. We could sort in any way, but we chose
2088   // case-insensitive sorting for consistency with the -help option
2089   // which prints out options in the case-insensitive alphabetical order.
2090   llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
2091     if (int X = A.compare_insensitive(B))
2092       return X < 0;
2093     return A.compare(B) > 0;
2094   });
2095 
2096   llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
2097 }
2098 
2099 bool Driver::HandleImmediateArgs(const Compilation &C) {
2100   // The order these options are handled in gcc is all over the place, but we
2101   // don't expect inconsistencies w.r.t. that to matter in practice.
2102 
2103   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
2104     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
2105     return false;
2106   }
2107 
2108   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
2109     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
2110     // return an answer which matches our definition of __VERSION__.
2111     llvm::outs() << CLANG_VERSION_STRING << "\n";
2112     return false;
2113   }
2114 
2115   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
2116     PrintDiagnosticCategories(llvm::outs());
2117     return false;
2118   }
2119 
2120   if (C.getArgs().hasArg(options::OPT_help) ||
2121       C.getArgs().hasArg(options::OPT__help_hidden)) {
2122     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
2123     return false;
2124   }
2125 
2126   if (C.getArgs().hasArg(options::OPT__version)) {
2127     // Follow gcc behavior and use stdout for --version and stderr for -v.
2128     PrintVersion(C, llvm::outs());
2129     return false;
2130   }
2131 
2132   if (C.getArgs().hasArg(options::OPT_v) ||
2133       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
2134       C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
2135     PrintVersion(C, llvm::errs());
2136     SuppressMissingInputWarning = true;
2137   }
2138 
2139   if (C.getArgs().hasArg(options::OPT_v)) {
2140     if (!SystemConfigDir.empty())
2141       llvm::errs() << "System configuration file directory: "
2142                    << SystemConfigDir << "\n";
2143     if (!UserConfigDir.empty())
2144       llvm::errs() << "User configuration file directory: "
2145                    << UserConfigDir << "\n";
2146   }
2147 
2148   const ToolChain &TC = C.getDefaultToolChain();
2149 
2150   if (C.getArgs().hasArg(options::OPT_v))
2151     TC.printVerboseInfo(llvm::errs());
2152 
2153   if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
2154     llvm::outs() << ResourceDir << '\n';
2155     return false;
2156   }
2157 
2158   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
2159     llvm::outs() << "programs: =";
2160     bool separator = false;
2161     // Print -B and COMPILER_PATH.
2162     for (const std::string &Path : PrefixDirs) {
2163       if (separator)
2164         llvm::outs() << llvm::sys::EnvPathSeparator;
2165       llvm::outs() << Path;
2166       separator = true;
2167     }
2168     for (const std::string &Path : TC.getProgramPaths()) {
2169       if (separator)
2170         llvm::outs() << llvm::sys::EnvPathSeparator;
2171       llvm::outs() << Path;
2172       separator = true;
2173     }
2174     llvm::outs() << "\n";
2175     llvm::outs() << "libraries: =" << ResourceDir;
2176 
2177     StringRef sysroot = C.getSysRoot();
2178 
2179     for (const std::string &Path : TC.getFilePaths()) {
2180       // Always print a separator. ResourceDir was the first item shown.
2181       llvm::outs() << llvm::sys::EnvPathSeparator;
2182       // Interpretation of leading '=' is needed only for NetBSD.
2183       if (Path[0] == '=')
2184         llvm::outs() << sysroot << Path.substr(1);
2185       else
2186         llvm::outs() << Path;
2187     }
2188     llvm::outs() << "\n";
2189     return false;
2190   }
2191 
2192   if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) {
2193     std::string RuntimePath;
2194     // Get the first existing path, if any.
2195     for (auto Path : TC.getRuntimePaths()) {
2196       if (getVFS().exists(Path)) {
2197         RuntimePath = Path;
2198         break;
2199       }
2200     }
2201     if (!RuntimePath.empty())
2202       llvm::outs() << RuntimePath << '\n';
2203     else
2204       llvm::outs() << TC.getCompilerRTPath() << '\n';
2205     return false;
2206   }
2207 
2208   if (C.getArgs().hasArg(options::OPT_print_diagnostic_options)) {
2209     std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags();
2210     for (std::size_t I = 0; I != Flags.size(); I += 2)
2211       llvm::outs() << "  " << Flags[I] << "\n  " << Flags[I + 1] << "\n\n";
2212     return false;
2213   }
2214 
2215   // FIXME: The following handlers should use a callback mechanism, we don't
2216   // know what the client would like to do.
2217   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
2218     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
2219     return false;
2220   }
2221 
2222   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
2223     StringRef ProgName = A->getValue();
2224 
2225     // Null program name cannot have a path.
2226     if (! ProgName.empty())
2227       llvm::outs() << GetProgramPath(ProgName, TC);
2228 
2229     llvm::outs() << "\n";
2230     return false;
2231   }
2232 
2233   if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
2234     StringRef PassedFlags = A->getValue();
2235     HandleAutocompletions(PassedFlags);
2236     return false;
2237   }
2238 
2239   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
2240     ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
2241     const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2242     RegisterEffectiveTriple TripleRAII(TC, Triple);
2243     switch (RLT) {
2244     case ToolChain::RLT_CompilerRT:
2245       llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
2246       break;
2247     case ToolChain::RLT_Libgcc:
2248       llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
2249       break;
2250     }
2251     return false;
2252   }
2253 
2254   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
2255     for (const Multilib &Multilib : TC.getMultilibs())
2256       llvm::outs() << Multilib << "\n";
2257     return false;
2258   }
2259 
2260   if (C.getArgs().hasArg(options::OPT_print_multi_flags)) {
2261     Multilib::flags_list ArgFlags = TC.getMultilibFlags(C.getArgs());
2262     llvm::StringSet<> ExpandedFlags = TC.getMultilibs().expandFlags(ArgFlags);
2263     std::set<llvm::StringRef> SortedFlags;
2264     for (const auto &FlagEntry : ExpandedFlags)
2265       SortedFlags.insert(FlagEntry.getKey());
2266     for (auto Flag : SortedFlags)
2267       llvm::outs() << Flag << '\n';
2268     return false;
2269   }
2270 
2271   if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
2272     for (const Multilib &Multilib : TC.getSelectedMultilibs()) {
2273       if (Multilib.gccSuffix().empty())
2274         llvm::outs() << ".\n";
2275       else {
2276         StringRef Suffix(Multilib.gccSuffix());
2277         assert(Suffix.front() == '/');
2278         llvm::outs() << Suffix.substr(1) << "\n";
2279       }
2280     }
2281     return false;
2282   }
2283 
2284   if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
2285     llvm::outs() << TC.getTripleString() << "\n";
2286     return false;
2287   }
2288 
2289   if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
2290     const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2291     llvm::outs() << Triple.getTriple() << "\n";
2292     return false;
2293   }
2294 
2295   if (C.getArgs().hasArg(options::OPT_print_targets)) {
2296     llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
2297     return false;
2298   }
2299 
2300   return true;
2301 }
2302 
2303 enum {
2304   TopLevelAction = 0,
2305   HeadSibAction = 1,
2306   OtherSibAction = 2,
2307 };
2308 
2309 // Display an action graph human-readably.  Action A is the "sink" node
2310 // and latest-occuring action. Traversal is in pre-order, visiting the
2311 // inputs to each action before printing the action itself.
2312 static unsigned PrintActions1(const Compilation &C, Action *A,
2313                               std::map<Action *, unsigned> &Ids,
2314                               Twine Indent = {}, int Kind = TopLevelAction) {
2315   if (Ids.count(A)) // A was already visited.
2316     return Ids[A];
2317 
2318   std::string str;
2319   llvm::raw_string_ostream os(str);
2320 
2321   auto getSibIndent = [](int K) -> Twine {
2322     return (K == HeadSibAction) ? "   " : (K == OtherSibAction) ? "|  " : "";
2323   };
2324 
2325   Twine SibIndent = Indent + getSibIndent(Kind);
2326   int SibKind = HeadSibAction;
2327   os << Action::getClassName(A->getKind()) << ", ";
2328   if (InputAction *IA = dyn_cast<InputAction>(A)) {
2329     os << "\"" << IA->getInputArg().getValue() << "\"";
2330   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
2331     os << '"' << BIA->getArchName() << '"' << ", {"
2332        << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
2333   } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
2334     bool IsFirst = true;
2335     OA->doOnEachDependence(
2336         [&](Action *A, const ToolChain *TC, const char *BoundArch) {
2337           assert(TC && "Unknown host toolchain");
2338           // E.g. for two CUDA device dependences whose bound arch is sm_20 and
2339           // sm_35 this will generate:
2340           // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
2341           // (nvptx64-nvidia-cuda:sm_35) {#ID}
2342           if (!IsFirst)
2343             os << ", ";
2344           os << '"';
2345           os << A->getOffloadingKindPrefix();
2346           os << " (";
2347           os << TC->getTriple().normalize();
2348           if (BoundArch)
2349             os << ":" << BoundArch;
2350           os << ")";
2351           os << '"';
2352           os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
2353           IsFirst = false;
2354           SibKind = OtherSibAction;
2355         });
2356   } else {
2357     const ActionList *AL = &A->getInputs();
2358 
2359     if (AL->size()) {
2360       const char *Prefix = "{";
2361       for (Action *PreRequisite : *AL) {
2362         os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
2363         Prefix = ", ";
2364         SibKind = OtherSibAction;
2365       }
2366       os << "}";
2367     } else
2368       os << "{}";
2369   }
2370 
2371   // Append offload info for all options other than the offloading action
2372   // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
2373   std::string offload_str;
2374   llvm::raw_string_ostream offload_os(offload_str);
2375   if (!isa<OffloadAction>(A)) {
2376     auto S = A->getOffloadingKindPrefix();
2377     if (!S.empty()) {
2378       offload_os << ", (" << S;
2379       if (A->getOffloadingArch())
2380         offload_os << ", " << A->getOffloadingArch();
2381       offload_os << ")";
2382     }
2383   }
2384 
2385   auto getSelfIndent = [](int K) -> Twine {
2386     return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
2387   };
2388 
2389   unsigned Id = Ids.size();
2390   Ids[A] = Id;
2391   llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
2392                << types::getTypeName(A->getType()) << offload_os.str() << "\n";
2393 
2394   return Id;
2395 }
2396 
2397 // Print the action graphs in a compilation C.
2398 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
2399 void Driver::PrintActions(const Compilation &C) const {
2400   std::map<Action *, unsigned> Ids;
2401   for (Action *A : C.getActions())
2402     PrintActions1(C, A, Ids);
2403 }
2404 
2405 /// Check whether the given input tree contains any compilation or
2406 /// assembly actions.
2407 static bool ContainsCompileOrAssembleAction(const Action *A) {
2408   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
2409       isa<AssembleJobAction>(A))
2410     return true;
2411 
2412   return llvm::any_of(A->inputs(), ContainsCompileOrAssembleAction);
2413 }
2414 
2415 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
2416                                    const InputList &BAInputs) const {
2417   DerivedArgList &Args = C.getArgs();
2418   ActionList &Actions = C.getActions();
2419   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
2420   // Collect the list of architectures. Duplicates are allowed, but should only
2421   // be handled once (in the order seen).
2422   llvm::StringSet<> ArchNames;
2423   SmallVector<const char *, 4> Archs;
2424   for (Arg *A : Args) {
2425     if (A->getOption().matches(options::OPT_arch)) {
2426       // Validate the option here; we don't save the type here because its
2427       // particular spelling may participate in other driver choices.
2428       llvm::Triple::ArchType Arch =
2429           tools::darwin::getArchTypeForMachOArchName(A->getValue());
2430       if (Arch == llvm::Triple::UnknownArch) {
2431         Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
2432         continue;
2433       }
2434 
2435       A->claim();
2436       if (ArchNames.insert(A->getValue()).second)
2437         Archs.push_back(A->getValue());
2438     }
2439   }
2440 
2441   // When there is no explicit arch for this platform, make sure we still bind
2442   // the architecture (to the default) so that -Xarch_ is handled correctly.
2443   if (!Archs.size())
2444     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
2445 
2446   ActionList SingleActions;
2447   BuildActions(C, Args, BAInputs, SingleActions);
2448 
2449   // Add in arch bindings for every top level action, as well as lipo and
2450   // dsymutil steps if needed.
2451   for (Action* Act : SingleActions) {
2452     // Make sure we can lipo this kind of output. If not (and it is an actual
2453     // output) then we disallow, since we can't create an output file with the
2454     // right name without overwriting it. We could remove this oddity by just
2455     // changing the output names to include the arch, which would also fix
2456     // -save-temps. Compatibility wins for now.
2457 
2458     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
2459       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
2460           << types::getTypeName(Act->getType());
2461 
2462     ActionList Inputs;
2463     for (unsigned i = 0, e = Archs.size(); i != e; ++i)
2464       Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
2465 
2466     // Lipo if necessary, we do it this way because we need to set the arch flag
2467     // so that -Xarch_ gets overwritten.
2468     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2469       Actions.append(Inputs.begin(), Inputs.end());
2470     else
2471       Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2472 
2473     // Handle debug info queries.
2474     Arg *A = Args.getLastArg(options::OPT_g_Group);
2475     bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2476                             !A->getOption().matches(options::OPT_gstabs);
2477     if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2478         ContainsCompileOrAssembleAction(Actions.back())) {
2479 
2480       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2481       // have a compile input. We need to run 'dsymutil' ourselves in such cases
2482       // because the debug info will refer to a temporary object file which
2483       // will be removed at the end of the compilation process.
2484       if (Act->getType() == types::TY_Image) {
2485         ActionList Inputs;
2486         Inputs.push_back(Actions.back());
2487         Actions.pop_back();
2488         Actions.push_back(
2489             C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2490       }
2491 
2492       // Verify the debug info output.
2493       if (Args.hasArg(options::OPT_verify_debug_info)) {
2494         Action* LastAction = Actions.back();
2495         Actions.pop_back();
2496         Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2497             LastAction, types::TY_Nothing));
2498       }
2499     }
2500   }
2501 }
2502 
2503 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2504                                     types::ID Ty, bool TypoCorrect) const {
2505   if (!getCheckInputsExist())
2506     return true;
2507 
2508   // stdin always exists.
2509   if (Value == "-")
2510     return true;
2511 
2512   // If it's a header to be found in the system or user search path, then defer
2513   // complaints about its absence until those searches can be done.  When we
2514   // are definitely processing headers for C++20 header units, extend this to
2515   // allow the user to put "-fmodule-header -xc++-header vector" for example.
2516   if (Ty == types::TY_CXXSHeader || Ty == types::TY_CXXUHeader ||
2517       (ModulesModeCXX20 && Ty == types::TY_CXXHeader))
2518     return true;
2519 
2520   if (getVFS().exists(Value))
2521     return true;
2522 
2523   if (TypoCorrect) {
2524     // Check if the filename is a typo for an option flag. OptTable thinks
2525     // that all args that are not known options and that start with / are
2526     // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2527     // the option `/diagnostics:caret` than a reference to a file in the root
2528     // directory.
2529     unsigned IncludedFlagsBitmask;
2530     unsigned ExcludedFlagsBitmask;
2531     std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2532         getIncludeExcludeOptionFlagMasks(IsCLMode());
2533     std::string Nearest;
2534     if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2535                               ExcludedFlagsBitmask) <= 1) {
2536       Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2537           << Value << Nearest;
2538       return false;
2539     }
2540   }
2541 
2542   // In CL mode, don't error on apparently non-existent linker inputs, because
2543   // they can be influenced by linker flags the clang driver might not
2544   // understand.
2545   // Examples:
2546   // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver
2547   //   module look for an MSVC installation in the registry. (We could ask
2548   //   the MSVCToolChain object if it can find `ole32.lib`, but the logic to
2549   //   look in the registry might move into lld-link in the future so that
2550   //   lld-link invocations in non-MSVC shells just work too.)
2551   // - `clang-cl ... /link ...` can pass arbitrary flags to the linker,
2552   //   including /libpath:, which is used to find .lib and .obj files.
2553   // So do not diagnose this on the driver level. Rely on the linker diagnosing
2554   // it. (If we don't end up invoking the linker, this means we'll emit a
2555   // "'linker' input unused [-Wunused-command-line-argument]" warning instead
2556   // of an error.)
2557   //
2558   // Only do this skip after the typo correction step above. `/Brepo` is treated
2559   // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit
2560   // an error if we have a flag that's within an edit distance of 1 from a
2561   // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the
2562   // driver in the unlikely case they run into this.)
2563   //
2564   // Don't do this for inputs that start with a '/', else we'd pass options
2565   // like /libpath: through to the linker silently.
2566   //
2567   // Emitting an error for linker inputs can also cause incorrect diagnostics
2568   // with the gcc driver. The command
2569   //     clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o
2570   // will make lld look for some/dir/file.o, while we will diagnose here that
2571   // `/file.o` does not exist. However, configure scripts check if
2572   // `clang /GR-` compiles without error to see if the compiler is cl.exe,
2573   // so we can't downgrade diagnostics for `/GR-` from an error to a warning
2574   // in cc mode. (We can in cl mode because cl.exe itself only warns on
2575   // unknown flags.)
2576   if (IsCLMode() && Ty == types::TY_Object && !Value.startswith("/"))
2577     return true;
2578 
2579   Diag(clang::diag::err_drv_no_such_file) << Value;
2580   return false;
2581 }
2582 
2583 // Get the C++20 Header Unit type corresponding to the input type.
2584 static types::ID CXXHeaderUnitType(ModuleHeaderMode HM) {
2585   switch (HM) {
2586   case HeaderMode_User:
2587     return types::TY_CXXUHeader;
2588   case HeaderMode_System:
2589     return types::TY_CXXSHeader;
2590   case HeaderMode_Default:
2591     break;
2592   case HeaderMode_None:
2593     llvm_unreachable("should not be called in this case");
2594   }
2595   return types::TY_CXXHUHeader;
2596 }
2597 
2598 // Construct a the list of inputs and their types.
2599 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2600                          InputList &Inputs) const {
2601   const llvm::opt::OptTable &Opts = getOpts();
2602   // Track the current user specified (-x) input. We also explicitly track the
2603   // argument used to set the type; we only want to claim the type when we
2604   // actually use it, so we warn about unused -x arguments.
2605   types::ID InputType = types::TY_Nothing;
2606   Arg *InputTypeArg = nullptr;
2607 
2608   // The last /TC or /TP option sets the input type to C or C++ globally.
2609   if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2610                                          options::OPT__SLASH_TP)) {
2611     InputTypeArg = TCTP;
2612     InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2613                     ? types::TY_C
2614                     : types::TY_CXX;
2615 
2616     Arg *Previous = nullptr;
2617     bool ShowNote = false;
2618     for (Arg *A :
2619          Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2620       if (Previous) {
2621         Diag(clang::diag::warn_drv_overriding_flag_option)
2622           << Previous->getSpelling() << A->getSpelling();
2623         ShowNote = true;
2624       }
2625       Previous = A;
2626     }
2627     if (ShowNote)
2628       Diag(clang::diag::note_drv_t_option_is_global);
2629   }
2630 
2631   // Warn -x after last input file has no effect
2632   if (!IsCLMode()) {
2633     Arg *LastXArg = Args.getLastArgNoClaim(options::OPT_x);
2634     Arg *LastInputArg = Args.getLastArgNoClaim(options::OPT_INPUT);
2635     if (LastXArg && LastInputArg &&
2636         LastInputArg->getIndex() < LastXArg->getIndex())
2637       Diag(clang::diag::warn_drv_unused_x) << LastXArg->getValue();
2638   } else {
2639     // In CL mode suggest /TC or /TP since -x doesn't make sense if passed via
2640     // /clang:.
2641     if (auto *A = Args.getLastArg(options::OPT_x))
2642       Diag(diag::err_drv_unsupported_opt_with_suggestion)
2643           << A->getAsString(Args) << "/TC' or '/TP";
2644   }
2645 
2646   for (Arg *A : Args) {
2647     if (A->getOption().getKind() == Option::InputClass) {
2648       const char *Value = A->getValue();
2649       types::ID Ty = types::TY_INVALID;
2650 
2651       // Infer the input type if necessary.
2652       if (InputType == types::TY_Nothing) {
2653         // If there was an explicit arg for this, claim it.
2654         if (InputTypeArg)
2655           InputTypeArg->claim();
2656 
2657         // stdin must be handled specially.
2658         if (memcmp(Value, "-", 2) == 0) {
2659           if (IsFlangMode()) {
2660             Ty = types::TY_Fortran;
2661           } else {
2662             // If running with -E, treat as a C input (this changes the
2663             // builtin macros, for example). This may be overridden by -ObjC
2664             // below.
2665             //
2666             // Otherwise emit an error but still use a valid type to avoid
2667             // spurious errors (e.g., no inputs).
2668             assert(!CCGenDiagnostics && "stdin produces no crash reproducer");
2669             if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2670               Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2671                               : clang::diag::err_drv_unknown_stdin_type);
2672             Ty = types::TY_C;
2673           }
2674         } else {
2675           // Otherwise lookup by extension.
2676           // Fallback is C if invoked as C preprocessor, C++ if invoked with
2677           // clang-cl /E, or Object otherwise.
2678           // We use a host hook here because Darwin at least has its own
2679           // idea of what .s is.
2680           if (const char *Ext = strrchr(Value, '.'))
2681             Ty = TC.LookupTypeForExtension(Ext + 1);
2682 
2683           if (Ty == types::TY_INVALID) {
2684             if (IsCLMode() && (Args.hasArgNoClaim(options::OPT_E) || CCGenDiagnostics))
2685               Ty = types::TY_CXX;
2686             else if (CCCIsCPP() || CCGenDiagnostics)
2687               Ty = types::TY_C;
2688             else
2689               Ty = types::TY_Object;
2690           }
2691 
2692           // If the driver is invoked as C++ compiler (like clang++ or c++) it
2693           // should autodetect some input files as C++ for g++ compatibility.
2694           if (CCCIsCXX()) {
2695             types::ID OldTy = Ty;
2696             Ty = types::lookupCXXTypeForCType(Ty);
2697 
2698             // Do not complain about foo.h, when we are known to be processing
2699             // it as a C++20 header unit.
2700             if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode()))
2701               Diag(clang::diag::warn_drv_treating_input_as_cxx)
2702                   << getTypeName(OldTy) << getTypeName(Ty);
2703           }
2704 
2705           // If running with -fthinlto-index=, extensions that normally identify
2706           // native object files actually identify LLVM bitcode files.
2707           if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2708               Ty == types::TY_Object)
2709             Ty = types::TY_LLVM_BC;
2710         }
2711 
2712         // -ObjC and -ObjC++ override the default language, but only for "source
2713         // files". We just treat everything that isn't a linker input as a
2714         // source file.
2715         //
2716         // FIXME: Clean this up if we move the phase sequence into the type.
2717         if (Ty != types::TY_Object) {
2718           if (Args.hasArg(options::OPT_ObjC))
2719             Ty = types::TY_ObjC;
2720           else if (Args.hasArg(options::OPT_ObjCXX))
2721             Ty = types::TY_ObjCXX;
2722         }
2723 
2724         // Disambiguate headers that are meant to be header units from those
2725         // intended to be PCH.  Avoid missing '.h' cases that are counted as
2726         // C headers by default - we know we are in C++ mode and we do not
2727         // want to issue a complaint about compiling things in the wrong mode.
2728         if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) &&
2729             hasHeaderMode())
2730           Ty = CXXHeaderUnitType(CXX20HeaderType);
2731       } else {
2732         assert(InputTypeArg && "InputType set w/o InputTypeArg");
2733         if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2734           // If emulating cl.exe, make sure that /TC and /TP don't affect input
2735           // object files.
2736           const char *Ext = strrchr(Value, '.');
2737           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2738             Ty = types::TY_Object;
2739         }
2740         if (Ty == types::TY_INVALID) {
2741           Ty = InputType;
2742           InputTypeArg->claim();
2743         }
2744       }
2745 
2746       if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2747         Inputs.push_back(std::make_pair(Ty, A));
2748 
2749     } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2750       StringRef Value = A->getValue();
2751       if (DiagnoseInputExistence(Args, Value, types::TY_C,
2752                                  /*TypoCorrect=*/false)) {
2753         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2754         Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2755       }
2756       A->claim();
2757     } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2758       StringRef Value = A->getValue();
2759       if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2760                                  /*TypoCorrect=*/false)) {
2761         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2762         Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2763       }
2764       A->claim();
2765     } else if (A->getOption().hasFlag(options::LinkerInput)) {
2766       // Just treat as object type, we could make a special type for this if
2767       // necessary.
2768       Inputs.push_back(std::make_pair(types::TY_Object, A));
2769 
2770     } else if (A->getOption().matches(options::OPT_x)) {
2771       InputTypeArg = A;
2772       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2773       A->claim();
2774 
2775       // Follow gcc behavior and treat as linker input for invalid -x
2776       // options. Its not clear why we shouldn't just revert to unknown; but
2777       // this isn't very important, we might as well be bug compatible.
2778       if (!InputType) {
2779         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2780         InputType = types::TY_Object;
2781       }
2782 
2783       // If the user has put -fmodule-header{,=} then we treat C++ headers as
2784       // header unit inputs.  So we 'promote' -xc++-header appropriately.
2785       if (InputType == types::TY_CXXHeader && hasHeaderMode())
2786         InputType = CXXHeaderUnitType(CXX20HeaderType);
2787     } else if (A->getOption().getID() == options::OPT_U) {
2788       assert(A->getNumValues() == 1 && "The /U option has one value.");
2789       StringRef Val = A->getValue(0);
2790       if (Val.find_first_of("/\\") != StringRef::npos) {
2791         // Warn about e.g. "/Users/me/myfile.c".
2792         Diag(diag::warn_slash_u_filename) << Val;
2793         Diag(diag::note_use_dashdash);
2794       }
2795     }
2796   }
2797   if (CCCIsCPP() && Inputs.empty()) {
2798     // If called as standalone preprocessor, stdin is processed
2799     // if no other input is present.
2800     Arg *A = MakeInputArg(Args, Opts, "-");
2801     Inputs.push_back(std::make_pair(types::TY_C, A));
2802   }
2803 }
2804 
2805 namespace {
2806 /// Provides a convenient interface for different programming models to generate
2807 /// the required device actions.
2808 class OffloadingActionBuilder final {
2809   /// Flag used to trace errors in the builder.
2810   bool IsValid = false;
2811 
2812   /// The compilation that is using this builder.
2813   Compilation &C;
2814 
2815   /// Map between an input argument and the offload kinds used to process it.
2816   std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2817 
2818   /// Map between a host action and its originating input argument.
2819   std::map<Action *, const Arg *> HostActionToInputArgMap;
2820 
2821   /// Builder interface. It doesn't build anything or keep any state.
2822   class DeviceActionBuilder {
2823   public:
2824     typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2825 
2826     enum ActionBuilderReturnCode {
2827       // The builder acted successfully on the current action.
2828       ABRT_Success,
2829       // The builder didn't have to act on the current action.
2830       ABRT_Inactive,
2831       // The builder was successful and requested the host action to not be
2832       // generated.
2833       ABRT_Ignore_Host,
2834     };
2835 
2836   protected:
2837     /// Compilation associated with this builder.
2838     Compilation &C;
2839 
2840     /// Tool chains associated with this builder. The same programming
2841     /// model may have associated one or more tool chains.
2842     SmallVector<const ToolChain *, 2> ToolChains;
2843 
2844     /// The derived arguments associated with this builder.
2845     DerivedArgList &Args;
2846 
2847     /// The inputs associated with this builder.
2848     const Driver::InputList &Inputs;
2849 
2850     /// The associated offload kind.
2851     Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2852 
2853   public:
2854     DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2855                         const Driver::InputList &Inputs,
2856                         Action::OffloadKind AssociatedOffloadKind)
2857         : C(C), Args(Args), Inputs(Inputs),
2858           AssociatedOffloadKind(AssociatedOffloadKind) {}
2859     virtual ~DeviceActionBuilder() {}
2860 
2861     /// Fill up the array \a DA with all the device dependences that should be
2862     /// added to the provided host action \a HostAction. By default it is
2863     /// inactive.
2864     virtual ActionBuilderReturnCode
2865     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2866                          phases::ID CurPhase, phases::ID FinalPhase,
2867                          PhasesTy &Phases) {
2868       return ABRT_Inactive;
2869     }
2870 
2871     /// Update the state to include the provided host action \a HostAction as a
2872     /// dependency of the current device action. By default it is inactive.
2873     virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) {
2874       return ABRT_Inactive;
2875     }
2876 
2877     /// Append top level actions generated by the builder.
2878     virtual void appendTopLevelActions(ActionList &AL) {}
2879 
2880     /// Append linker device actions generated by the builder.
2881     virtual void appendLinkDeviceActions(ActionList &AL) {}
2882 
2883     /// Append linker host action generated by the builder.
2884     virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2885 
2886     /// Append linker actions generated by the builder.
2887     virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2888 
2889     /// Initialize the builder. Return true if any initialization errors are
2890     /// found.
2891     virtual bool initialize() { return false; }
2892 
2893     /// Return true if the builder can use bundling/unbundling.
2894     virtual bool canUseBundlerUnbundler() const { return false; }
2895 
2896     /// Return true if this builder is valid. We have a valid builder if we have
2897     /// associated device tool chains.
2898     bool isValid() { return !ToolChains.empty(); }
2899 
2900     /// Return the associated offload kind.
2901     Action::OffloadKind getAssociatedOffloadKind() {
2902       return AssociatedOffloadKind;
2903     }
2904   };
2905 
2906   /// Base class for CUDA/HIP action builder. It injects device code in
2907   /// the host backend action.
2908   class CudaActionBuilderBase : public DeviceActionBuilder {
2909   protected:
2910     /// Flags to signal if the user requested host-only or device-only
2911     /// compilation.
2912     bool CompileHostOnly = false;
2913     bool CompileDeviceOnly = false;
2914     bool EmitLLVM = false;
2915     bool EmitAsm = false;
2916 
2917     /// ID to identify each device compilation. For CUDA it is simply the
2918     /// GPU arch string. For HIP it is either the GPU arch string or GPU
2919     /// arch string plus feature strings delimited by a plus sign, e.g.
2920     /// gfx906+xnack.
2921     struct TargetID {
2922       /// Target ID string which is persistent throughout the compilation.
2923       const char *ID;
2924       TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); }
2925       TargetID(const char *ID) : ID(ID) {}
2926       operator const char *() { return ID; }
2927       operator StringRef() { return StringRef(ID); }
2928     };
2929     /// List of GPU architectures to use in this compilation.
2930     SmallVector<TargetID, 4> GpuArchList;
2931 
2932     /// The CUDA actions for the current input.
2933     ActionList CudaDeviceActions;
2934 
2935     /// The CUDA fat binary if it was generated for the current input.
2936     Action *CudaFatBinary = nullptr;
2937 
2938     /// Flag that is set to true if this builder acted on the current input.
2939     bool IsActive = false;
2940 
2941     /// Flag for -fgpu-rdc.
2942     bool Relocatable = false;
2943 
2944     /// Default GPU architecture if there's no one specified.
2945     CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2946 
2947     /// Method to generate compilation unit ID specified by option
2948     /// '-fuse-cuid='.
2949     enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid };
2950     UseCUIDKind UseCUID = CUID_Hash;
2951 
2952     /// Compilation unit ID specified by option '-cuid='.
2953     StringRef FixedCUID;
2954 
2955   public:
2956     CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2957                           const Driver::InputList &Inputs,
2958                           Action::OffloadKind OFKind)
2959         : DeviceActionBuilder(C, Args, Inputs, OFKind) {
2960 
2961       CompileDeviceOnly = C.getDriver().offloadDeviceOnly();
2962       Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2963                                  options::OPT_fno_gpu_rdc, /*Default=*/false);
2964     }
2965 
2966     ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override {
2967       // While generating code for CUDA, we only depend on the host input action
2968       // to trigger the creation of all the CUDA device actions.
2969 
2970       // If we are dealing with an input action, replicate it for each GPU
2971       // architecture. If we are in host-only mode we return 'success' so that
2972       // the host uses the CUDA offload kind.
2973       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2974         assert(!GpuArchList.empty() &&
2975                "We should have at least one GPU architecture.");
2976 
2977         // If the host input is not CUDA or HIP, we don't need to bother about
2978         // this input.
2979         if (!(IA->getType() == types::TY_CUDA ||
2980               IA->getType() == types::TY_HIP ||
2981               IA->getType() == types::TY_PP_HIP)) {
2982           // The builder will ignore this input.
2983           IsActive = false;
2984           return ABRT_Inactive;
2985         }
2986 
2987         // Set the flag to true, so that the builder acts on the current input.
2988         IsActive = true;
2989 
2990         if (CompileHostOnly)
2991           return ABRT_Success;
2992 
2993         // Replicate inputs for each GPU architecture.
2994         auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2995                                                  : types::TY_CUDA_DEVICE;
2996         std::string CUID = FixedCUID.str();
2997         if (CUID.empty()) {
2998           if (UseCUID == CUID_Random)
2999             CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
3000                                    /*LowerCase=*/true);
3001           else if (UseCUID == CUID_Hash) {
3002             llvm::MD5 Hasher;
3003             llvm::MD5::MD5Result Hash;
3004             SmallString<256> RealPath;
3005             llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath,
3006                                      /*expand_tilde=*/true);
3007             Hasher.update(RealPath);
3008             for (auto *A : Args) {
3009               if (A->getOption().matches(options::OPT_INPUT))
3010                 continue;
3011               Hasher.update(A->getAsString(Args));
3012             }
3013             Hasher.final(Hash);
3014             CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
3015           }
3016         }
3017         IA->setId(CUID);
3018 
3019         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3020           CudaDeviceActions.push_back(
3021               C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId()));
3022         }
3023 
3024         return ABRT_Success;
3025       }
3026 
3027       // If this is an unbundling action use it as is for each CUDA toolchain.
3028       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
3029 
3030         // If -fgpu-rdc is disabled, should not unbundle since there is no
3031         // device code to link.
3032         if (UA->getType() == types::TY_Object && !Relocatable)
3033           return ABRT_Inactive;
3034 
3035         CudaDeviceActions.clear();
3036         auto *IA = cast<InputAction>(UA->getInputs().back());
3037         std::string FileName = IA->getInputArg().getAsString(Args);
3038         // Check if the type of the file is the same as the action. Do not
3039         // unbundle it if it is not. Do not unbundle .so files, for example,
3040         // which are not object files. Files with extension ".lib" is classified
3041         // as TY_Object but they are actually archives, therefore should not be
3042         // unbundled here as objects. They will be handled at other places.
3043         const StringRef LibFileExt = ".lib";
3044         if (IA->getType() == types::TY_Object &&
3045             (!llvm::sys::path::has_extension(FileName) ||
3046              types::lookupTypeForExtension(
3047                  llvm::sys::path::extension(FileName).drop_front()) !=
3048                  types::TY_Object ||
3049              llvm::sys::path::extension(FileName) == LibFileExt))
3050           return ABRT_Inactive;
3051 
3052         for (auto Arch : GpuArchList) {
3053           CudaDeviceActions.push_back(UA);
3054           UA->registerDependentActionInfo(ToolChains[0], Arch,
3055                                           AssociatedOffloadKind);
3056         }
3057         IsActive = true;
3058         return ABRT_Success;
3059       }
3060 
3061       return IsActive ? ABRT_Success : ABRT_Inactive;
3062     }
3063 
3064     void appendTopLevelActions(ActionList &AL) override {
3065       // Utility to append actions to the top level list.
3066       auto AddTopLevel = [&](Action *A, TargetID TargetID) {
3067         OffloadAction::DeviceDependences Dep;
3068         Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind);
3069         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
3070       };
3071 
3072       // If we have a fat binary, add it to the list.
3073       if (CudaFatBinary) {
3074         AddTopLevel(CudaFatBinary, CudaArch::UNUSED);
3075         CudaDeviceActions.clear();
3076         CudaFatBinary = nullptr;
3077         return;
3078       }
3079 
3080       if (CudaDeviceActions.empty())
3081         return;
3082 
3083       // If we have CUDA actions at this point, that's because we have a have
3084       // partial compilation, so we should have an action for each GPU
3085       // architecture.
3086       assert(CudaDeviceActions.size() == GpuArchList.size() &&
3087              "Expecting one action per GPU architecture.");
3088       assert(ToolChains.size() == 1 &&
3089              "Expecting to have a single CUDA toolchain.");
3090       for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
3091         AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
3092 
3093       CudaDeviceActions.clear();
3094     }
3095 
3096     /// Get canonicalized offload arch option. \returns empty StringRef if the
3097     /// option is invalid.
3098     virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0;
3099 
3100     virtual std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
3101     getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0;
3102 
3103     bool initialize() override {
3104       assert(AssociatedOffloadKind == Action::OFK_Cuda ||
3105              AssociatedOffloadKind == Action::OFK_HIP);
3106 
3107       // We don't need to support CUDA.
3108       if (AssociatedOffloadKind == Action::OFK_Cuda &&
3109           !C.hasOffloadToolChain<Action::OFK_Cuda>())
3110         return false;
3111 
3112       // We don't need to support HIP.
3113       if (AssociatedOffloadKind == Action::OFK_HIP &&
3114           !C.hasOffloadToolChain<Action::OFK_HIP>())
3115         return false;
3116 
3117       const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
3118       assert(HostTC && "No toolchain for host compilation.");
3119       if (HostTC->getTriple().isNVPTX() ||
3120           HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
3121         // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
3122         // an error and abort pipeline construction early so we don't trip
3123         // asserts that assume device-side compilation.
3124         C.getDriver().Diag(diag::err_drv_cuda_host_arch)
3125             << HostTC->getTriple().getArchName();
3126         return true;
3127       }
3128 
3129       ToolChains.push_back(
3130           AssociatedOffloadKind == Action::OFK_Cuda
3131               ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3132               : C.getSingleOffloadToolChain<Action::OFK_HIP>());
3133 
3134       CompileHostOnly = C.getDriver().offloadHostOnly();
3135       EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
3136       EmitAsm = Args.getLastArg(options::OPT_S);
3137       FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ);
3138       if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) {
3139         StringRef UseCUIDStr = A->getValue();
3140         UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr)
3141                       .Case("hash", CUID_Hash)
3142                       .Case("random", CUID_Random)
3143                       .Case("none", CUID_None)
3144                       .Default(CUID_Invalid);
3145         if (UseCUID == CUID_Invalid) {
3146           C.getDriver().Diag(diag::err_drv_invalid_value)
3147               << A->getAsString(Args) << UseCUIDStr;
3148           C.setContainsError();
3149           return true;
3150         }
3151       }
3152 
3153       // --offload and --offload-arch options are mutually exclusive.
3154       if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
3155           Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
3156                              options::OPT_no_offload_arch_EQ)) {
3157         C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch"
3158                                                              << "--offload";
3159       }
3160 
3161       // Collect all offload arch parameters, removing duplicates.
3162       std::set<StringRef> GpuArchs;
3163       bool Error = false;
3164       for (Arg *A : Args) {
3165         if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
3166               A->getOption().matches(options::OPT_no_offload_arch_EQ)))
3167           continue;
3168         A->claim();
3169 
3170         for (StringRef ArchStr : llvm::split(A->getValue(), ",")) {
3171           if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
3172               ArchStr == "all") {
3173             GpuArchs.clear();
3174           } else if (ArchStr == "native") {
3175             const ToolChain &TC = *ToolChains.front();
3176             auto GPUsOrErr = ToolChains.front()->getSystemGPUArchs(Args);
3177             if (!GPUsOrErr) {
3178               TC.getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
3179                   << llvm::Triple::getArchTypeName(TC.getArch())
3180                   << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
3181               continue;
3182             }
3183 
3184             for (auto GPU : *GPUsOrErr) {
3185               GpuArchs.insert(Args.MakeArgString(GPU));
3186             }
3187           } else {
3188             ArchStr = getCanonicalOffloadArch(ArchStr);
3189             if (ArchStr.empty()) {
3190               Error = true;
3191             } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
3192               GpuArchs.insert(ArchStr);
3193             else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
3194               GpuArchs.erase(ArchStr);
3195             else
3196               llvm_unreachable("Unexpected option.");
3197           }
3198         }
3199       }
3200 
3201       auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs);
3202       if (ConflictingArchs) {
3203         C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
3204             << ConflictingArchs->first << ConflictingArchs->second;
3205         C.setContainsError();
3206         return true;
3207       }
3208 
3209       // Collect list of GPUs remaining in the set.
3210       for (auto Arch : GpuArchs)
3211         GpuArchList.push_back(Arch.data());
3212 
3213       // Default to sm_20 which is the lowest common denominator for
3214       // supported GPUs.  sm_20 code should work correctly, if
3215       // suboptimally, on all newer GPUs.
3216       if (GpuArchList.empty()) {
3217         if (ToolChains.front()->getTriple().isSPIRV())
3218           GpuArchList.push_back(CudaArch::Generic);
3219         else
3220           GpuArchList.push_back(DefaultCudaArch);
3221       }
3222 
3223       return Error;
3224     }
3225   };
3226 
3227   /// \brief CUDA action builder. It injects device code in the host backend
3228   /// action.
3229   class CudaActionBuilder final : public CudaActionBuilderBase {
3230   public:
3231     CudaActionBuilder(Compilation &C, DerivedArgList &Args,
3232                       const Driver::InputList &Inputs)
3233         : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
3234       DefaultCudaArch = CudaArch::SM_35;
3235     }
3236 
3237     StringRef getCanonicalOffloadArch(StringRef ArchStr) override {
3238       CudaArch Arch = StringToCudaArch(ArchStr);
3239       if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) {
3240         C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
3241         return StringRef();
3242       }
3243       return CudaArchToString(Arch);
3244     }
3245 
3246     std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
3247     getConflictOffloadArchCombination(
3248         const std::set<StringRef> &GpuArchs) override {
3249       return std::nullopt;
3250     }
3251 
3252     ActionBuilderReturnCode
3253     getDeviceDependences(OffloadAction::DeviceDependences &DA,
3254                          phases::ID CurPhase, phases::ID FinalPhase,
3255                          PhasesTy &Phases) override {
3256       if (!IsActive)
3257         return ABRT_Inactive;
3258 
3259       // If we don't have more CUDA actions, we don't have any dependences to
3260       // create for the host.
3261       if (CudaDeviceActions.empty())
3262         return ABRT_Success;
3263 
3264       assert(CudaDeviceActions.size() == GpuArchList.size() &&
3265              "Expecting one action per GPU architecture.");
3266       assert(!CompileHostOnly &&
3267              "Not expecting CUDA actions in host-only compilation.");
3268 
3269       // If we are generating code for the device or we are in a backend phase,
3270       // we attempt to generate the fat binary. We compile each arch to ptx and
3271       // assemble to cubin, then feed the cubin *and* the ptx into a device
3272       // "link" action, which uses fatbinary to combine these cubins into one
3273       // fatbin.  The fatbin is then an input to the host action if not in
3274       // device-only mode.
3275       if (CompileDeviceOnly || CurPhase == phases::Backend) {
3276         ActionList DeviceActions;
3277         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3278           // Produce the device action from the current phase up to the assemble
3279           // phase.
3280           for (auto Ph : Phases) {
3281             // Skip the phases that were already dealt with.
3282             if (Ph < CurPhase)
3283               continue;
3284             // We have to be consistent with the host final phase.
3285             if (Ph > FinalPhase)
3286               break;
3287 
3288             CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
3289                 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
3290 
3291             if (Ph == phases::Assemble)
3292               break;
3293           }
3294 
3295           // If we didn't reach the assemble phase, we can't generate the fat
3296           // binary. We don't need to generate the fat binary if we are not in
3297           // device-only mode.
3298           if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
3299               CompileDeviceOnly)
3300             continue;
3301 
3302           Action *AssembleAction = CudaDeviceActions[I];
3303           assert(AssembleAction->getType() == types::TY_Object);
3304           assert(AssembleAction->getInputs().size() == 1);
3305 
3306           Action *BackendAction = AssembleAction->getInputs()[0];
3307           assert(BackendAction->getType() == types::TY_PP_Asm);
3308 
3309           for (auto &A : {AssembleAction, BackendAction}) {
3310             OffloadAction::DeviceDependences DDep;
3311             DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda);
3312             DeviceActions.push_back(
3313                 C.MakeAction<OffloadAction>(DDep, A->getType()));
3314           }
3315         }
3316 
3317         // We generate the fat binary if we have device input actions.
3318         if (!DeviceActions.empty()) {
3319           CudaFatBinary =
3320               C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
3321 
3322           if (!CompileDeviceOnly) {
3323             DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3324                    Action::OFK_Cuda);
3325             // Clear the fat binary, it is already a dependence to an host
3326             // action.
3327             CudaFatBinary = nullptr;
3328           }
3329 
3330           // Remove the CUDA actions as they are already connected to an host
3331           // action or fat binary.
3332           CudaDeviceActions.clear();
3333         }
3334 
3335         // We avoid creating host action in device-only mode.
3336         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3337       } else if (CurPhase > phases::Backend) {
3338         // If we are past the backend phase and still have a device action, we
3339         // don't have to do anything as this action is already a device
3340         // top-level action.
3341         return ABRT_Success;
3342       }
3343 
3344       assert(CurPhase < phases::Backend && "Generating single CUDA "
3345                                            "instructions should only occur "
3346                                            "before the backend phase!");
3347 
3348       // By default, we produce an action for each device arch.
3349       for (Action *&A : CudaDeviceActions)
3350         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
3351 
3352       return ABRT_Success;
3353     }
3354   };
3355   /// \brief HIP action builder. It injects device code in the host backend
3356   /// action.
3357   class HIPActionBuilder final : public CudaActionBuilderBase {
3358     /// The linker inputs obtained for each device arch.
3359     SmallVector<ActionList, 8> DeviceLinkerInputs;
3360     // The default bundling behavior depends on the type of output, therefore
3361     // BundleOutput needs to be tri-value: None, true, or false.
3362     // Bundle code objects except --no-gpu-output is specified for device
3363     // only compilation. Bundle other type of output files only if
3364     // --gpu-bundle-output is specified for device only compilation.
3365     std::optional<bool> BundleOutput;
3366     std::optional<bool> EmitReloc;
3367 
3368   public:
3369     HIPActionBuilder(Compilation &C, DerivedArgList &Args,
3370                      const Driver::InputList &Inputs)
3371         : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
3372 
3373       DefaultCudaArch = CudaArch::GFX906;
3374 
3375       if (Args.hasArg(options::OPT_fhip_emit_relocatable,
3376                       options::OPT_fno_hip_emit_relocatable)) {
3377         EmitReloc = Args.hasFlag(options::OPT_fhip_emit_relocatable,
3378                                  options::OPT_fno_hip_emit_relocatable, false);
3379 
3380         if (*EmitReloc) {
3381           if (Relocatable) {
3382             C.getDriver().Diag(diag::err_opt_not_valid_with_opt)
3383                 << "-fhip-emit-relocatable"
3384                 << "-fgpu-rdc";
3385           }
3386 
3387           if (!CompileDeviceOnly) {
3388             C.getDriver().Diag(diag::err_opt_not_valid_without_opt)
3389                 << "-fhip-emit-relocatable"
3390                 << "--cuda-device-only";
3391           }
3392         }
3393       }
3394 
3395       if (Args.hasArg(options::OPT_gpu_bundle_output,
3396                       options::OPT_no_gpu_bundle_output))
3397         BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output,
3398                                     options::OPT_no_gpu_bundle_output, true) &&
3399                        (!EmitReloc || !*EmitReloc);
3400     }
3401 
3402     bool canUseBundlerUnbundler() const override { return true; }
3403 
3404     StringRef getCanonicalOffloadArch(StringRef IdStr) override {
3405       llvm::StringMap<bool> Features;
3406       // getHIPOffloadTargetTriple() is known to return valid value as it has
3407       // been called successfully in the CreateOffloadingDeviceToolChains().
3408       auto ArchStr = parseTargetID(
3409           *getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), IdStr,
3410           &Features);
3411       if (!ArchStr) {
3412         C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr;
3413         C.setContainsError();
3414         return StringRef();
3415       }
3416       auto CanId = getCanonicalTargetID(*ArchStr, Features);
3417       return Args.MakeArgStringRef(CanId);
3418     };
3419 
3420     std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
3421     getConflictOffloadArchCombination(
3422         const std::set<StringRef> &GpuArchs) override {
3423       return getConflictTargetIDCombination(GpuArchs);
3424     }
3425 
3426     ActionBuilderReturnCode
3427     getDeviceDependences(OffloadAction::DeviceDependences &DA,
3428                          phases::ID CurPhase, phases::ID FinalPhase,
3429                          PhasesTy &Phases) override {
3430       if (!IsActive)
3431         return ABRT_Inactive;
3432 
3433       // amdgcn does not support linking of object files, therefore we skip
3434       // backend and assemble phases to output LLVM IR. Except for generating
3435       // non-relocatable device code, where we generate fat binary for device
3436       // code and pass to host in Backend phase.
3437       if (CudaDeviceActions.empty())
3438         return ABRT_Success;
3439 
3440       assert(((CurPhase == phases::Link && Relocatable) ||
3441               CudaDeviceActions.size() == GpuArchList.size()) &&
3442              "Expecting one action per GPU architecture.");
3443       assert(!CompileHostOnly &&
3444              "Not expecting HIP actions in host-only compilation.");
3445 
3446       bool ShouldLink = !EmitReloc || !*EmitReloc;
3447 
3448       if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
3449           !EmitAsm && ShouldLink) {
3450         // If we are in backend phase, we attempt to generate the fat binary.
3451         // We compile each arch to IR and use a link action to generate code
3452         // object containing ISA. Then we use a special "link" action to create
3453         // a fat binary containing all the code objects for different GPU's.
3454         // The fat binary is then an input to the host action.
3455         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3456           if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) {
3457             // When LTO is enabled, skip the backend and assemble phases and
3458             // use lld to link the bitcode.
3459             ActionList AL;
3460             AL.push_back(CudaDeviceActions[I]);
3461             // Create a link action to link device IR with device library
3462             // and generate ISA.
3463             CudaDeviceActions[I] =
3464                 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3465           } else {
3466             // When LTO is not enabled, we follow the conventional
3467             // compiler phases, including backend and assemble phases.
3468             ActionList AL;
3469             Action *BackendAction = nullptr;
3470             if (ToolChains.front()->getTriple().isSPIRV()) {
3471               // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain
3472               // (HIPSPVToolChain) runs post-link LLVM IR passes.
3473               types::ID Output = Args.hasArg(options::OPT_S)
3474                                      ? types::TY_LLVM_IR
3475                                      : types::TY_LLVM_BC;
3476               BackendAction =
3477                   C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output);
3478             } else
3479               BackendAction = C.getDriver().ConstructPhaseAction(
3480                   C, Args, phases::Backend, CudaDeviceActions[I],
3481                   AssociatedOffloadKind);
3482             auto AssembleAction = C.getDriver().ConstructPhaseAction(
3483                 C, Args, phases::Assemble, BackendAction,
3484                 AssociatedOffloadKind);
3485             AL.push_back(AssembleAction);
3486             // Create a link action to link device IR with device library
3487             // and generate ISA.
3488             CudaDeviceActions[I] =
3489                 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3490           }
3491 
3492           // OffloadingActionBuilder propagates device arch until an offload
3493           // action. Since the next action for creating fatbin does
3494           // not have device arch, whereas the above link action and its input
3495           // have device arch, an offload action is needed to stop the null
3496           // device arch of the next action being propagated to the above link
3497           // action.
3498           OffloadAction::DeviceDependences DDep;
3499           DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3500                    AssociatedOffloadKind);
3501           CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3502               DDep, CudaDeviceActions[I]->getType());
3503         }
3504 
3505         if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3506           // Create HIP fat binary with a special "link" action.
3507           CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions,
3508                                                       types::TY_HIP_FATBIN);
3509 
3510           if (!CompileDeviceOnly) {
3511             DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3512                    AssociatedOffloadKind);
3513             // Clear the fat binary, it is already a dependence to an host
3514             // action.
3515             CudaFatBinary = nullptr;
3516           }
3517 
3518           // Remove the CUDA actions as they are already connected to an host
3519           // action or fat binary.
3520           CudaDeviceActions.clear();
3521         }
3522 
3523         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3524       } else if (CurPhase == phases::Link) {
3525         if (!ShouldLink)
3526           return ABRT_Success;
3527         // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
3528         // This happens to each device action originated from each input file.
3529         // Later on, device actions in DeviceLinkerInputs are used to create
3530         // device link actions in appendLinkDependences and the created device
3531         // link actions are passed to the offload action as device dependence.
3532         DeviceLinkerInputs.resize(CudaDeviceActions.size());
3533         auto LI = DeviceLinkerInputs.begin();
3534         for (auto *A : CudaDeviceActions) {
3535           LI->push_back(A);
3536           ++LI;
3537         }
3538 
3539         // We will pass the device action as a host dependence, so we don't
3540         // need to do anything else with them.
3541         CudaDeviceActions.clear();
3542         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3543       }
3544 
3545       // By default, we produce an action for each device arch.
3546       for (Action *&A : CudaDeviceActions)
3547         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
3548                                                AssociatedOffloadKind);
3549 
3550       if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput &&
3551           *BundleOutput) {
3552         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3553           OffloadAction::DeviceDependences DDep;
3554           DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3555                    AssociatedOffloadKind);
3556           CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3557               DDep, CudaDeviceActions[I]->getType());
3558         }
3559         CudaFatBinary =
3560             C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions);
3561         CudaDeviceActions.clear();
3562       }
3563 
3564       return (CompileDeviceOnly &&
3565               (CurPhase == FinalPhase ||
3566                (!ShouldLink && CurPhase == phases::Assemble)))
3567                  ? ABRT_Ignore_Host
3568                  : ABRT_Success;
3569     }
3570 
3571     void appendLinkDeviceActions(ActionList &AL) override {
3572       if (DeviceLinkerInputs.size() == 0)
3573         return;
3574 
3575       assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
3576              "Linker inputs and GPU arch list sizes do not match.");
3577 
3578       ActionList Actions;
3579       unsigned I = 0;
3580       // Append a new link action for each device.
3581       // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
3582       for (auto &LI : DeviceLinkerInputs) {
3583 
3584         types::ID Output = Args.hasArg(options::OPT_emit_llvm)
3585                                    ? types::TY_LLVM_BC
3586                                    : types::TY_Image;
3587 
3588         auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(LI, Output);
3589         // Linking all inputs for the current GPU arch.
3590         // LI contains all the inputs for the linker.
3591         OffloadAction::DeviceDependences DeviceLinkDeps;
3592         DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
3593             GpuArchList[I], AssociatedOffloadKind);
3594         Actions.push_back(C.MakeAction<OffloadAction>(
3595             DeviceLinkDeps, DeviceLinkAction->getType()));
3596         ++I;
3597       }
3598       DeviceLinkerInputs.clear();
3599 
3600       // If emitting LLVM, do not generate final host/device compilation action
3601       if (Args.hasArg(options::OPT_emit_llvm)) {
3602           AL.append(Actions);
3603           return;
3604       }
3605 
3606       // Create a host object from all the device images by embedding them
3607       // in a fat binary for mixed host-device compilation. For device-only
3608       // compilation, creates a fat binary.
3609       OffloadAction::DeviceDependences DDeps;
3610       if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3611         auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>(
3612             Actions,
3613             CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object);
3614         DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr,
3615                   AssociatedOffloadKind);
3616         // Offload the host object to the host linker.
3617         AL.push_back(
3618             C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
3619       } else {
3620         AL.append(Actions);
3621       }
3622     }
3623 
3624     Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
3625 
3626     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3627   };
3628 
3629   ///
3630   /// TODO: Add the implementation for other specialized builders here.
3631   ///
3632 
3633   /// Specialized builders being used by this offloading action builder.
3634   SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3635 
3636   /// Flag set to true if all valid builders allow file bundling/unbundling.
3637   bool CanUseBundler;
3638 
3639 public:
3640   OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3641                           const Driver::InputList &Inputs)
3642       : C(C) {
3643     // Create a specialized builder for each device toolchain.
3644 
3645     IsValid = true;
3646 
3647     // Create a specialized builder for CUDA.
3648     SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3649 
3650     // Create a specialized builder for HIP.
3651     SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3652 
3653     //
3654     // TODO: Build other specialized builders here.
3655     //
3656 
3657     // Initialize all the builders, keeping track of errors. If all valid
3658     // builders agree that we can use bundling, set the flag to true.
3659     unsigned ValidBuilders = 0u;
3660     unsigned ValidBuildersSupportingBundling = 0u;
3661     for (auto *SB : SpecializedBuilders) {
3662       IsValid = IsValid && !SB->initialize();
3663 
3664       // Update the counters if the builder is valid.
3665       if (SB->isValid()) {
3666         ++ValidBuilders;
3667         if (SB->canUseBundlerUnbundler())
3668           ++ValidBuildersSupportingBundling;
3669       }
3670     }
3671     CanUseBundler =
3672         ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3673   }
3674 
3675   ~OffloadingActionBuilder() {
3676     for (auto *SB : SpecializedBuilders)
3677       delete SB;
3678   }
3679 
3680   /// Record a host action and its originating input argument.
3681   void recordHostAction(Action *HostAction, const Arg *InputArg) {
3682     assert(HostAction && "Invalid host action");
3683     assert(InputArg && "Invalid input argument");
3684     auto Loc = HostActionToInputArgMap.find(HostAction);
3685     if (Loc == HostActionToInputArgMap.end())
3686       HostActionToInputArgMap[HostAction] = InputArg;
3687     assert(HostActionToInputArgMap[HostAction] == InputArg &&
3688            "host action mapped to multiple input arguments");
3689   }
3690 
3691   /// Generate an action that adds device dependences (if any) to a host action.
3692   /// If no device dependence actions exist, just return the host action \a
3693   /// HostAction. If an error is found or if no builder requires the host action
3694   /// to be generated, return nullptr.
3695   Action *
3696   addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3697                                    phases::ID CurPhase, phases::ID FinalPhase,
3698                                    DeviceActionBuilder::PhasesTy &Phases) {
3699     if (!IsValid)
3700       return nullptr;
3701 
3702     if (SpecializedBuilders.empty())
3703       return HostAction;
3704 
3705     assert(HostAction && "Invalid host action!");
3706     recordHostAction(HostAction, InputArg);
3707 
3708     OffloadAction::DeviceDependences DDeps;
3709     // Check if all the programming models agree we should not emit the host
3710     // action. Also, keep track of the offloading kinds employed.
3711     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3712     unsigned InactiveBuilders = 0u;
3713     unsigned IgnoringBuilders = 0u;
3714     for (auto *SB : SpecializedBuilders) {
3715       if (!SB->isValid()) {
3716         ++InactiveBuilders;
3717         continue;
3718       }
3719       auto RetCode =
3720           SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3721 
3722       // If the builder explicitly says the host action should be ignored,
3723       // we need to increment the variable that tracks the builders that request
3724       // the host object to be ignored.
3725       if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3726         ++IgnoringBuilders;
3727 
3728       // Unless the builder was inactive for this action, we have to record the
3729       // offload kind because the host will have to use it.
3730       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3731         OffloadKind |= SB->getAssociatedOffloadKind();
3732     }
3733 
3734     // If all builders agree that the host object should be ignored, just return
3735     // nullptr.
3736     if (IgnoringBuilders &&
3737         SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3738       return nullptr;
3739 
3740     if (DDeps.getActions().empty())
3741       return HostAction;
3742 
3743     // We have dependences we need to bundle together. We use an offload action
3744     // for that.
3745     OffloadAction::HostDependence HDep(
3746         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3747         /*BoundArch=*/nullptr, DDeps);
3748     return C.MakeAction<OffloadAction>(HDep, DDeps);
3749   }
3750 
3751   /// Generate an action that adds a host dependence to a device action. The
3752   /// results will be kept in this action builder. Return true if an error was
3753   /// found.
3754   bool addHostDependenceToDeviceActions(Action *&HostAction,
3755                                         const Arg *InputArg) {
3756     if (!IsValid)
3757       return true;
3758 
3759     recordHostAction(HostAction, InputArg);
3760 
3761     // If we are supporting bundling/unbundling and the current action is an
3762     // input action of non-source file, we replace the host action by the
3763     // unbundling action. The bundler tool has the logic to detect if an input
3764     // is a bundle or not and if the input is not a bundle it assumes it is a
3765     // host file. Therefore it is safe to create an unbundling action even if
3766     // the input is not a bundle.
3767     if (CanUseBundler && isa<InputAction>(HostAction) &&
3768         InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3769         (!types::isSrcFile(HostAction->getType()) ||
3770          HostAction->getType() == types::TY_PP_HIP)) {
3771       auto UnbundlingHostAction =
3772           C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3773       UnbundlingHostAction->registerDependentActionInfo(
3774           C.getSingleOffloadToolChain<Action::OFK_Host>(),
3775           /*BoundArch=*/StringRef(), Action::OFK_Host);
3776       HostAction = UnbundlingHostAction;
3777       recordHostAction(HostAction, InputArg);
3778     }
3779 
3780     assert(HostAction && "Invalid host action!");
3781 
3782     // Register the offload kinds that are used.
3783     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3784     for (auto *SB : SpecializedBuilders) {
3785       if (!SB->isValid())
3786         continue;
3787 
3788       auto RetCode = SB->addDeviceDependences(HostAction);
3789 
3790       // Host dependences for device actions are not compatible with that same
3791       // action being ignored.
3792       assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3793              "Host dependence not expected to be ignored.!");
3794 
3795       // Unless the builder was inactive for this action, we have to record the
3796       // offload kind because the host will have to use it.
3797       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3798         OffloadKind |= SB->getAssociatedOffloadKind();
3799     }
3800 
3801     // Do not use unbundler if the Host does not depend on device action.
3802     if (OffloadKind == Action::OFK_None && CanUseBundler)
3803       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3804         HostAction = UA->getInputs().back();
3805 
3806     return false;
3807   }
3808 
3809   /// Add the offloading top level actions to the provided action list. This
3810   /// function can replace the host action by a bundling action if the
3811   /// programming models allow it.
3812   bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3813                              const Arg *InputArg) {
3814     if (HostAction)
3815       recordHostAction(HostAction, InputArg);
3816 
3817     // Get the device actions to be appended.
3818     ActionList OffloadAL;
3819     for (auto *SB : SpecializedBuilders) {
3820       if (!SB->isValid())
3821         continue;
3822       SB->appendTopLevelActions(OffloadAL);
3823     }
3824 
3825     // If we can use the bundler, replace the host action by the bundling one in
3826     // the resulting list. Otherwise, just append the device actions. For
3827     // device only compilation, HostAction is a null pointer, therefore only do
3828     // this when HostAction is not a null pointer.
3829     if (CanUseBundler && HostAction &&
3830         HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3831       // Add the host action to the list in order to create the bundling action.
3832       OffloadAL.push_back(HostAction);
3833 
3834       // We expect that the host action was just appended to the action list
3835       // before this method was called.
3836       assert(HostAction == AL.back() && "Host action not in the list??");
3837       HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3838       recordHostAction(HostAction, InputArg);
3839       AL.back() = HostAction;
3840     } else
3841       AL.append(OffloadAL.begin(), OffloadAL.end());
3842 
3843     // Propagate to the current host action (if any) the offload information
3844     // associated with the current input.
3845     if (HostAction)
3846       HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3847                                            /*BoundArch=*/nullptr);
3848     return false;
3849   }
3850 
3851   void appendDeviceLinkActions(ActionList &AL) {
3852     for (DeviceActionBuilder *SB : SpecializedBuilders) {
3853       if (!SB->isValid())
3854         continue;
3855       SB->appendLinkDeviceActions(AL);
3856     }
3857   }
3858 
3859   Action *makeHostLinkAction() {
3860     // Build a list of device linking actions.
3861     ActionList DeviceAL;
3862     appendDeviceLinkActions(DeviceAL);
3863     if (DeviceAL.empty())
3864       return nullptr;
3865 
3866     // Let builders add host linking actions.
3867     Action* HA = nullptr;
3868     for (DeviceActionBuilder *SB : SpecializedBuilders) {
3869       if (!SB->isValid())
3870         continue;
3871       HA = SB->appendLinkHostActions(DeviceAL);
3872       // This created host action has no originating input argument, therefore
3873       // needs to set its offloading kind directly.
3874       if (HA)
3875         HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(),
3876                                      /*BoundArch=*/nullptr);
3877     }
3878     return HA;
3879   }
3880 
3881   /// Processes the host linker action. This currently consists of replacing it
3882   /// with an offload action if there are device link objects and propagate to
3883   /// the host action all the offload kinds used in the current compilation. The
3884   /// resulting action is returned.
3885   Action *processHostLinkAction(Action *HostAction) {
3886     // Add all the dependences from the device linking actions.
3887     OffloadAction::DeviceDependences DDeps;
3888     for (auto *SB : SpecializedBuilders) {
3889       if (!SB->isValid())
3890         continue;
3891 
3892       SB->appendLinkDependences(DDeps);
3893     }
3894 
3895     // Calculate all the offload kinds used in the current compilation.
3896     unsigned ActiveOffloadKinds = 0u;
3897     for (auto &I : InputArgToOffloadKindMap)
3898       ActiveOffloadKinds |= I.second;
3899 
3900     // If we don't have device dependencies, we don't have to create an offload
3901     // action.
3902     if (DDeps.getActions().empty()) {
3903       // Set all the active offloading kinds to the link action. Given that it
3904       // is a link action it is assumed to depend on all actions generated so
3905       // far.
3906       HostAction->setHostOffloadInfo(ActiveOffloadKinds,
3907                                      /*BoundArch=*/nullptr);
3908       // Propagate active offloading kinds for each input to the link action.
3909       // Each input may have different active offloading kind.
3910       for (auto *A : HostAction->inputs()) {
3911         auto ArgLoc = HostActionToInputArgMap.find(A);
3912         if (ArgLoc == HostActionToInputArgMap.end())
3913           continue;
3914         auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second);
3915         if (OFKLoc == InputArgToOffloadKindMap.end())
3916           continue;
3917         A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr);
3918       }
3919       return HostAction;
3920     }
3921 
3922     // Create the offload action with all dependences. When an offload action
3923     // is created the kinds are propagated to the host action, so we don't have
3924     // to do that explicitly here.
3925     OffloadAction::HostDependence HDep(
3926         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3927         /*BoundArch*/ nullptr, ActiveOffloadKinds);
3928     return C.MakeAction<OffloadAction>(HDep, DDeps);
3929   }
3930 };
3931 } // anonymous namespace.
3932 
3933 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3934                              const InputList &Inputs,
3935                              ActionList &Actions) const {
3936 
3937   // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3938   Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3939   Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3940   if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3941     Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3942     Args.eraseArg(options::OPT__SLASH_Yc);
3943     Args.eraseArg(options::OPT__SLASH_Yu);
3944     YcArg = YuArg = nullptr;
3945   }
3946   if (YcArg && Inputs.size() > 1) {
3947     Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3948     Args.eraseArg(options::OPT__SLASH_Yc);
3949     YcArg = nullptr;
3950   }
3951 
3952   Arg *FinalPhaseArg;
3953   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3954 
3955   if (FinalPhase == phases::Link) {
3956     // Emitting LLVM while linking disabled except in HIPAMD Toolchain
3957     if (Args.hasArg(options::OPT_emit_llvm) && !Args.hasArg(options::OPT_hip_link))
3958       Diag(clang::diag::err_drv_emit_llvm_link);
3959     if (IsCLMode() && LTOMode != LTOK_None &&
3960         !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
3961              .equals_insensitive("lld"))
3962       Diag(clang::diag::err_drv_lto_without_lld);
3963 
3964     // If -dumpdir is not specified, give a default prefix derived from the link
3965     // output filename. For example, `clang -g -gsplit-dwarf a.c -o x` passes
3966     // `-dumpdir x-` to cc1. If -o is unspecified, use
3967     // stem(getDefaultImageName()) (usually stem("a.out") = "a").
3968     if (!Args.hasArg(options::OPT_dumpdir)) {
3969       Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o);
3970       Arg *Arg = Args.MakeSeparateArg(
3971           nullptr, getOpts().getOption(options::OPT_dumpdir),
3972           Args.MakeArgString(
3973               (FinalOutput ? FinalOutput->getValue()
3974                            : llvm::sys::path::stem(getDefaultImageName())) +
3975               "-"));
3976       Arg->claim();
3977       Args.append(Arg);
3978     }
3979   }
3980 
3981   if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3982     // If only preprocessing or /Y- is used, all pch handling is disabled.
3983     // Rather than check for it everywhere, just remove clang-cl pch-related
3984     // flags here.
3985     Args.eraseArg(options::OPT__SLASH_Fp);
3986     Args.eraseArg(options::OPT__SLASH_Yc);
3987     Args.eraseArg(options::OPT__SLASH_Yu);
3988     YcArg = YuArg = nullptr;
3989   }
3990 
3991   unsigned LastPLSize = 0;
3992   for (auto &I : Inputs) {
3993     types::ID InputType = I.first;
3994     const Arg *InputArg = I.second;
3995 
3996     auto PL = types::getCompilationPhases(InputType);
3997     LastPLSize = PL.size();
3998 
3999     // If the first step comes after the final phase we are doing as part of
4000     // this compilation, warn the user about it.
4001     phases::ID InitialPhase = PL[0];
4002     if (InitialPhase > FinalPhase) {
4003       if (InputArg->isClaimed())
4004         continue;
4005 
4006       // Claim here to avoid the more general unused warning.
4007       InputArg->claim();
4008 
4009       // Suppress all unused style warnings with -Qunused-arguments
4010       if (Args.hasArg(options::OPT_Qunused_arguments))
4011         continue;
4012 
4013       // Special case when final phase determined by binary name, rather than
4014       // by a command-line argument with a corresponding Arg.
4015       if (CCCIsCPP())
4016         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
4017             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
4018       // Special case '-E' warning on a previously preprocessed file to make
4019       // more sense.
4020       else if (InitialPhase == phases::Compile &&
4021                (Args.getLastArg(options::OPT__SLASH_EP,
4022                                 options::OPT__SLASH_P) ||
4023                 Args.getLastArg(options::OPT_E) ||
4024                 Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
4025                getPreprocessedType(InputType) == types::TY_INVALID)
4026         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
4027             << InputArg->getAsString(Args) << !!FinalPhaseArg
4028             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
4029       else
4030         Diag(clang::diag::warn_drv_input_file_unused)
4031             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
4032             << !!FinalPhaseArg
4033             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
4034       continue;
4035     }
4036 
4037     if (YcArg) {
4038       // Add a separate precompile phase for the compile phase.
4039       if (FinalPhase >= phases::Compile) {
4040         const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
4041         // Build the pipeline for the pch file.
4042         Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
4043         for (phases::ID Phase : types::getCompilationPhases(HeaderType))
4044           ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
4045         assert(ClangClPch);
4046         Actions.push_back(ClangClPch);
4047         // The driver currently exits after the first failed command.  This
4048         // relies on that behavior, to make sure if the pch generation fails,
4049         // the main compilation won't run.
4050         // FIXME: If the main compilation fails, the PCH generation should
4051         // probably not be considered successful either.
4052       }
4053     }
4054   }
4055 
4056   // If we are linking, claim any options which are obviously only used for
4057   // compilation.
4058   // FIXME: Understand why the last Phase List length is used here.
4059   if (FinalPhase == phases::Link && LastPLSize == 1) {
4060     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
4061     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
4062   }
4063 }
4064 
4065 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
4066                           const InputList &Inputs, ActionList &Actions) const {
4067   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
4068 
4069   if (!SuppressMissingInputWarning && Inputs.empty()) {
4070     Diag(clang::diag::err_drv_no_input_files);
4071     return;
4072   }
4073 
4074   // Diagnose misuse of /Fo.
4075   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
4076     StringRef V = A->getValue();
4077     if (Inputs.size() > 1 && !V.empty() &&
4078         !llvm::sys::path::is_separator(V.back())) {
4079       // Check whether /Fo tries to name an output file for multiple inputs.
4080       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
4081           << A->getSpelling() << V;
4082       Args.eraseArg(options::OPT__SLASH_Fo);
4083     }
4084   }
4085 
4086   // Diagnose misuse of /Fa.
4087   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
4088     StringRef V = A->getValue();
4089     if (Inputs.size() > 1 && !V.empty() &&
4090         !llvm::sys::path::is_separator(V.back())) {
4091       // Check whether /Fa tries to name an asm file for multiple inputs.
4092       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
4093           << A->getSpelling() << V;
4094       Args.eraseArg(options::OPT__SLASH_Fa);
4095     }
4096   }
4097 
4098   // Diagnose misuse of /o.
4099   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
4100     if (A->getValue()[0] == '\0') {
4101       // It has to have a value.
4102       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
4103       Args.eraseArg(options::OPT__SLASH_o);
4104     }
4105   }
4106 
4107   handleArguments(C, Args, Inputs, Actions);
4108 
4109   bool UseNewOffloadingDriver =
4110       C.isOffloadingHostKind(Action::OFK_OpenMP) ||
4111       Args.hasFlag(options::OPT_offload_new_driver,
4112                    options::OPT_no_offload_new_driver, false);
4113 
4114   // Builder to be used to build offloading actions.
4115   std::unique_ptr<OffloadingActionBuilder> OffloadBuilder =
4116       !UseNewOffloadingDriver
4117           ? std::make_unique<OffloadingActionBuilder>(C, Args, Inputs)
4118           : nullptr;
4119 
4120   // Construct the actions to perform.
4121   ExtractAPIJobAction *ExtractAPIAction = nullptr;
4122   ActionList LinkerInputs;
4123   ActionList MergerInputs;
4124 
4125   for (auto &I : Inputs) {
4126     types::ID InputType = I.first;
4127     const Arg *InputArg = I.second;
4128 
4129     auto PL = types::getCompilationPhases(*this, Args, InputType);
4130     if (PL.empty())
4131       continue;
4132 
4133     auto FullPL = types::getCompilationPhases(InputType);
4134 
4135     // Build the pipeline for this file.
4136     Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
4137 
4138     // Use the current host action in any of the offloading actions, if
4139     // required.
4140     if (!UseNewOffloadingDriver)
4141       if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg))
4142         break;
4143 
4144     for (phases::ID Phase : PL) {
4145 
4146       // Add any offload action the host action depends on.
4147       if (!UseNewOffloadingDriver)
4148         Current = OffloadBuilder->addDeviceDependencesToHostAction(
4149             Current, InputArg, Phase, PL.back(), FullPL);
4150       if (!Current)
4151         break;
4152 
4153       // Queue linker inputs.
4154       if (Phase == phases::Link) {
4155         assert(Phase == PL.back() && "linking must be final compilation step.");
4156         // We don't need to generate additional link commands if emitting AMD
4157         // bitcode or compiling only for the offload device
4158         if (!(C.getInputArgs().hasArg(options::OPT_hip_link) &&
4159               (C.getInputArgs().hasArg(options::OPT_emit_llvm))) &&
4160             !offloadDeviceOnly())
4161           LinkerInputs.push_back(Current);
4162         Current = nullptr;
4163         break;
4164       }
4165 
4166       // TODO: Consider removing this because the merged may not end up being
4167       // the final Phase in the pipeline. Perhaps the merged could just merge
4168       // and then pass an artifact of some sort to the Link Phase.
4169       // Queue merger inputs.
4170       if (Phase == phases::IfsMerge) {
4171         assert(Phase == PL.back() && "merging must be final compilation step.");
4172         MergerInputs.push_back(Current);
4173         Current = nullptr;
4174         break;
4175       }
4176 
4177       if (Phase == phases::Precompile && ExtractAPIAction) {
4178         ExtractAPIAction->addHeaderInput(Current);
4179         Current = nullptr;
4180         break;
4181       }
4182 
4183       // FIXME: Should we include any prior module file outputs as inputs of
4184       // later actions in the same command line?
4185 
4186       // Otherwise construct the appropriate action.
4187       Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
4188 
4189       // We didn't create a new action, so we will just move to the next phase.
4190       if (NewCurrent == Current)
4191         continue;
4192 
4193       if (auto *EAA = dyn_cast<ExtractAPIJobAction>(NewCurrent))
4194         ExtractAPIAction = EAA;
4195 
4196       Current = NewCurrent;
4197 
4198       // Try to build the offloading actions and add the result as a dependency
4199       // to the host.
4200       if (UseNewOffloadingDriver)
4201         Current = BuildOffloadingActions(C, Args, I, Current);
4202       // Use the current host action in any of the offloading actions, if
4203       // required.
4204       else if (OffloadBuilder->addHostDependenceToDeviceActions(Current,
4205                                                                 InputArg))
4206         break;
4207 
4208       if (Current->getType() == types::TY_Nothing)
4209         break;
4210     }
4211 
4212     // If we ended with something, add to the output list.
4213     if (Current)
4214       Actions.push_back(Current);
4215 
4216     // Add any top level actions generated for offloading.
4217     if (!UseNewOffloadingDriver)
4218       OffloadBuilder->appendTopLevelActions(Actions, Current, InputArg);
4219     else if (Current)
4220       Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4221                                         /*BoundArch=*/nullptr);
4222   }
4223 
4224   // Add a link action if necessary.
4225 
4226   if (LinkerInputs.empty()) {
4227     Arg *FinalPhaseArg;
4228     if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link)
4229       if (!UseNewOffloadingDriver)
4230         OffloadBuilder->appendDeviceLinkActions(Actions);
4231   }
4232 
4233   if (!LinkerInputs.empty()) {
4234     if (!UseNewOffloadingDriver)
4235       if (Action *Wrapper = OffloadBuilder->makeHostLinkAction())
4236         LinkerInputs.push_back(Wrapper);
4237     Action *LA;
4238     // Check if this Linker Job should emit a static library.
4239     if (ShouldEmitStaticLibrary(Args)) {
4240       LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
4241     } else if (UseNewOffloadingDriver ||
4242                Args.hasArg(options::OPT_offload_link)) {
4243       LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image);
4244       LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4245                                    /*BoundArch=*/nullptr);
4246     } else {
4247       LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
4248     }
4249     if (!UseNewOffloadingDriver)
4250       LA = OffloadBuilder->processHostLinkAction(LA);
4251     Actions.push_back(LA);
4252   }
4253 
4254   // Add an interface stubs merge action if necessary.
4255   if (!MergerInputs.empty())
4256     Actions.push_back(
4257         C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4258 
4259   if (Args.hasArg(options::OPT_emit_interface_stubs)) {
4260     auto PhaseList = types::getCompilationPhases(
4261         types::TY_IFS_CPP,
4262         Args.hasArg(options::OPT_c) ? phases::Compile : phases::IfsMerge);
4263 
4264     ActionList MergerInputs;
4265 
4266     for (auto &I : Inputs) {
4267       types::ID InputType = I.first;
4268       const Arg *InputArg = I.second;
4269 
4270       // Currently clang and the llvm assembler do not support generating symbol
4271       // stubs from assembly, so we skip the input on asm files. For ifs files
4272       // we rely on the normal pipeline setup in the pipeline setup code above.
4273       if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
4274           InputType == types::TY_Asm)
4275         continue;
4276 
4277       Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
4278 
4279       for (auto Phase : PhaseList) {
4280         switch (Phase) {
4281         default:
4282           llvm_unreachable(
4283               "IFS Pipeline can only consist of Compile followed by IfsMerge.");
4284         case phases::Compile: {
4285           // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
4286           // files where the .o file is located. The compile action can not
4287           // handle this.
4288           if (InputType == types::TY_Object)
4289             break;
4290 
4291           Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
4292           break;
4293         }
4294         case phases::IfsMerge: {
4295           assert(Phase == PhaseList.back() &&
4296                  "merging must be final compilation step.");
4297           MergerInputs.push_back(Current);
4298           Current = nullptr;
4299           break;
4300         }
4301         }
4302       }
4303 
4304       // If we ended with something, add to the output list.
4305       if (Current)
4306         Actions.push_back(Current);
4307     }
4308 
4309     // Add an interface stubs merge action if necessary.
4310     if (!MergerInputs.empty())
4311       Actions.push_back(
4312           C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4313   }
4314 
4315   // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
4316   // Compile phase that prints out supported cpu models and quits.
4317   if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
4318     // Use the -mcpu=? flag as the dummy input to cc1.
4319     Actions.clear();
4320     Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
4321     Actions.push_back(
4322         C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
4323     for (auto &I : Inputs)
4324       I.second->claim();
4325   }
4326 
4327   // Call validator for dxil when -Vd not in Args.
4328   if (C.getDefaultToolChain().getTriple().isDXIL()) {
4329     // Only add action when needValidation.
4330     const auto &TC =
4331         static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain());
4332     if (TC.requiresValidation(Args)) {
4333       Action *LastAction = Actions.back();
4334       Actions.push_back(C.MakeAction<BinaryAnalyzeJobAction>(
4335           LastAction, types::TY_DX_CONTAINER));
4336     }
4337   }
4338 
4339   // Claim ignored clang-cl options.
4340   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
4341 }
4342 
4343 /// Returns the canonical name for the offloading architecture when using a HIP
4344 /// or CUDA architecture.
4345 static StringRef getCanonicalArchString(Compilation &C,
4346                                         const llvm::opt::DerivedArgList &Args,
4347                                         StringRef ArchStr,
4348                                         const llvm::Triple &Triple,
4349                                         bool SuppressError = false) {
4350   // Lookup the CUDA / HIP architecture string. Only report an error if we were
4351   // expecting the triple to be only NVPTX / AMDGPU.
4352   CudaArch Arch = StringToCudaArch(getProcessorFromTargetID(Triple, ArchStr));
4353   if (!SuppressError && Triple.isNVPTX() &&
4354       (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch))) {
4355     C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4356         << "CUDA" << ArchStr;
4357     return StringRef();
4358   } else if (!SuppressError && Triple.isAMDGPU() &&
4359              (Arch == CudaArch::UNKNOWN || !IsAMDGpuArch(Arch))) {
4360     C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4361         << "HIP" << ArchStr;
4362     return StringRef();
4363   }
4364 
4365   if (IsNVIDIAGpuArch(Arch))
4366     return Args.MakeArgStringRef(CudaArchToString(Arch));
4367 
4368   if (IsAMDGpuArch(Arch)) {
4369     llvm::StringMap<bool> Features;
4370     auto HIPTriple = getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs());
4371     if (!HIPTriple)
4372       return StringRef();
4373     auto Arch = parseTargetID(*HIPTriple, ArchStr, &Features);
4374     if (!Arch) {
4375       C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr;
4376       C.setContainsError();
4377       return StringRef();
4378     }
4379     return Args.MakeArgStringRef(getCanonicalTargetID(*Arch, Features));
4380   }
4381 
4382   // If the input isn't CUDA or HIP just return the architecture.
4383   return ArchStr;
4384 }
4385 
4386 /// Checks if the set offloading architectures does not conflict. Returns the
4387 /// incompatible pair if a conflict occurs.
4388 static std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
4389 getConflictOffloadArchCombination(const llvm::DenseSet<StringRef> &Archs,
4390                                   llvm::Triple Triple) {
4391   if (!Triple.isAMDGPU())
4392     return std::nullopt;
4393 
4394   std::set<StringRef> ArchSet;
4395   llvm::copy(Archs, std::inserter(ArchSet, ArchSet.begin()));
4396   return getConflictTargetIDCombination(ArchSet);
4397 }
4398 
4399 llvm::DenseSet<StringRef>
4400 Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
4401                         Action::OffloadKind Kind, const ToolChain *TC,
4402                         bool SuppressError) const {
4403   if (!TC)
4404     TC = &C.getDefaultToolChain();
4405 
4406   // --offload and --offload-arch options are mutually exclusive.
4407   if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
4408       Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
4409                          options::OPT_no_offload_arch_EQ)) {
4410     C.getDriver().Diag(diag::err_opt_not_valid_with_opt)
4411         << "--offload"
4412         << (Args.hasArgNoClaim(options::OPT_offload_arch_EQ)
4413                 ? "--offload-arch"
4414                 : "--no-offload-arch");
4415   }
4416 
4417   if (KnownArchs.contains(TC))
4418     return KnownArchs.lookup(TC);
4419 
4420   llvm::DenseSet<StringRef> Archs;
4421   for (auto *Arg : Args) {
4422     // Extract any '--[no-]offload-arch' arguments intended for this toolchain.
4423     std::unique_ptr<llvm::opt::Arg> ExtractedArg = nullptr;
4424     if (Arg->getOption().matches(options::OPT_Xopenmp_target_EQ) &&
4425         ToolChain::getOpenMPTriple(Arg->getValue(0)) == TC->getTriple()) {
4426       Arg->claim();
4427       unsigned Index = Args.getBaseArgs().MakeIndex(Arg->getValue(1));
4428       ExtractedArg = getOpts().ParseOneArg(Args, Index);
4429       Arg = ExtractedArg.get();
4430     }
4431 
4432     // Add or remove the seen architectures in order of appearance. If an
4433     // invalid architecture is given we simply exit.
4434     if (Arg->getOption().matches(options::OPT_offload_arch_EQ)) {
4435       for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4436         if (Arch == "native" || Arch.empty()) {
4437           auto GPUsOrErr = TC->getSystemGPUArchs(Args);
4438           if (!GPUsOrErr) {
4439             if (SuppressError)
4440               llvm::consumeError(GPUsOrErr.takeError());
4441             else
4442               TC->getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
4443                   << llvm::Triple::getArchTypeName(TC->getArch())
4444                   << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
4445             continue;
4446           }
4447 
4448           for (auto ArchStr : *GPUsOrErr) {
4449             Archs.insert(
4450                 getCanonicalArchString(C, Args, Args.MakeArgString(ArchStr),
4451                                        TC->getTriple(), SuppressError));
4452           }
4453         } else {
4454           StringRef ArchStr = getCanonicalArchString(
4455               C, Args, Arch, TC->getTriple(), SuppressError);
4456           if (ArchStr.empty())
4457             return Archs;
4458           Archs.insert(ArchStr);
4459         }
4460       }
4461     } else if (Arg->getOption().matches(options::OPT_no_offload_arch_EQ)) {
4462       for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4463         if (Arch == "all") {
4464           Archs.clear();
4465         } else {
4466           StringRef ArchStr = getCanonicalArchString(
4467               C, Args, Arch, TC->getTriple(), SuppressError);
4468           if (ArchStr.empty())
4469             return Archs;
4470           Archs.erase(ArchStr);
4471         }
4472       }
4473     }
4474   }
4475 
4476   if (auto ConflictingArchs =
4477           getConflictOffloadArchCombination(Archs, TC->getTriple())) {
4478     C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
4479         << ConflictingArchs->first << ConflictingArchs->second;
4480     C.setContainsError();
4481   }
4482 
4483   // Skip filling defaults if we're just querying what is availible.
4484   if (SuppressError)
4485     return Archs;
4486 
4487   if (Archs.empty()) {
4488     if (Kind == Action::OFK_Cuda)
4489       Archs.insert(CudaArchToString(CudaArch::CudaDefault));
4490     else if (Kind == Action::OFK_HIP)
4491       Archs.insert(CudaArchToString(CudaArch::HIPDefault));
4492     else if (Kind == Action::OFK_OpenMP)
4493       Archs.insert(StringRef());
4494   } else {
4495     Args.ClaimAllArgs(options::OPT_offload_arch_EQ);
4496     Args.ClaimAllArgs(options::OPT_no_offload_arch_EQ);
4497   }
4498 
4499   return Archs;
4500 }
4501 
4502 Action *Driver::BuildOffloadingActions(Compilation &C,
4503                                        llvm::opt::DerivedArgList &Args,
4504                                        const InputTy &Input,
4505                                        Action *HostAction) const {
4506   // Don't build offloading actions if explicitly disabled or we do not have a
4507   // valid source input and compile action to embed it in. If preprocessing only
4508   // ignore embedding.
4509   if (offloadHostOnly() || !types::isSrcFile(Input.first) ||
4510       !(isa<CompileJobAction>(HostAction) ||
4511         getFinalPhase(Args) == phases::Preprocess))
4512     return HostAction;
4513 
4514   ActionList OffloadActions;
4515   OffloadAction::DeviceDependences DDeps;
4516 
4517   const Action::OffloadKind OffloadKinds[] = {
4518       Action::OFK_OpenMP, Action::OFK_Cuda, Action::OFK_HIP};
4519 
4520   for (Action::OffloadKind Kind : OffloadKinds) {
4521     SmallVector<const ToolChain *, 2> ToolChains;
4522     ActionList DeviceActions;
4523 
4524     auto TCRange = C.getOffloadToolChains(Kind);
4525     for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI)
4526       ToolChains.push_back(TI->second);
4527 
4528     if (ToolChains.empty())
4529       continue;
4530 
4531     types::ID InputType = Input.first;
4532     const Arg *InputArg = Input.second;
4533 
4534     // The toolchain can be active for unsupported file types.
4535     if ((Kind == Action::OFK_Cuda && !types::isCuda(InputType)) ||
4536         (Kind == Action::OFK_HIP && !types::isHIP(InputType)))
4537       continue;
4538 
4539     // Get the product of all bound architectures and toolchains.
4540     SmallVector<std::pair<const ToolChain *, StringRef>> TCAndArchs;
4541     for (const ToolChain *TC : ToolChains)
4542       for (StringRef Arch : getOffloadArchs(C, Args, Kind, TC))
4543         TCAndArchs.push_back(std::make_pair(TC, Arch));
4544 
4545     for (unsigned I = 0, E = TCAndArchs.size(); I != E; ++I)
4546       DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType));
4547 
4548     if (DeviceActions.empty())
4549       return HostAction;
4550 
4551     auto PL = types::getCompilationPhases(*this, Args, InputType);
4552 
4553     for (phases::ID Phase : PL) {
4554       if (Phase == phases::Link) {
4555         assert(Phase == PL.back() && "linking must be final compilation step.");
4556         break;
4557       }
4558 
4559       auto TCAndArch = TCAndArchs.begin();
4560       for (Action *&A : DeviceActions) {
4561         if (A->getType() == types::TY_Nothing)
4562           continue;
4563 
4564         // Propagate the ToolChain so we can use it in ConstructPhaseAction.
4565         A->propagateDeviceOffloadInfo(Kind, TCAndArch->second.data(),
4566                                       TCAndArch->first);
4567         A = ConstructPhaseAction(C, Args, Phase, A, Kind);
4568 
4569         if (isa<CompileJobAction>(A) && isa<CompileJobAction>(HostAction) &&
4570             Kind == Action::OFK_OpenMP &&
4571             HostAction->getType() != types::TY_Nothing) {
4572           // OpenMP offloading has a dependency on the host compile action to
4573           // identify which declarations need to be emitted. This shouldn't be
4574           // collapsed with any other actions so we can use it in the device.
4575           HostAction->setCannotBeCollapsedWithNextDependentAction();
4576           OffloadAction::HostDependence HDep(
4577               *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4578               TCAndArch->second.data(), Kind);
4579           OffloadAction::DeviceDependences DDep;
4580           DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4581           A = C.MakeAction<OffloadAction>(HDep, DDep);
4582         }
4583 
4584         ++TCAndArch;
4585       }
4586     }
4587 
4588     // Compiling HIP in non-RDC mode requires linking each action individually.
4589     for (Action *&A : DeviceActions) {
4590       if ((A->getType() != types::TY_Object &&
4591            A->getType() != types::TY_LTO_BC) ||
4592           Kind != Action::OFK_HIP ||
4593           Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
4594         continue;
4595       ActionList LinkerInput = {A};
4596       A = C.MakeAction<LinkJobAction>(LinkerInput, types::TY_Image);
4597     }
4598 
4599     auto TCAndArch = TCAndArchs.begin();
4600     for (Action *A : DeviceActions) {
4601       DDeps.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4602       OffloadAction::DeviceDependences DDep;
4603       DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4604       OffloadActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType()));
4605       ++TCAndArch;
4606     }
4607   }
4608 
4609   if (offloadDeviceOnly())
4610     return C.MakeAction<OffloadAction>(DDeps, types::TY_Nothing);
4611 
4612   if (OffloadActions.empty())
4613     return HostAction;
4614 
4615   OffloadAction::DeviceDependences DDep;
4616   if (C.isOffloadingHostKind(Action::OFK_Cuda) &&
4617       !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) {
4618     // If we are not in RDC-mode we just emit the final CUDA fatbinary for
4619     // each translation unit without requiring any linking.
4620     Action *FatbinAction =
4621         C.MakeAction<LinkJobAction>(OffloadActions, types::TY_CUDA_FATBIN);
4622     DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_Cuda>(),
4623              nullptr, Action::OFK_Cuda);
4624   } else if (C.isOffloadingHostKind(Action::OFK_HIP) &&
4625              !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4626                            false)) {
4627     // If we are not in RDC-mode we just emit the final HIP fatbinary for each
4628     // translation unit, linking each input individually.
4629     Action *FatbinAction =
4630         C.MakeAction<LinkJobAction>(OffloadActions, types::TY_HIP_FATBIN);
4631     DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_HIP>(),
4632              nullptr, Action::OFK_HIP);
4633   } else {
4634     // Package all the offloading actions into a single output that can be
4635     // embedded in the host and linked.
4636     Action *PackagerAction =
4637         C.MakeAction<OffloadPackagerJobAction>(OffloadActions, types::TY_Image);
4638     DDep.add(*PackagerAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4639              nullptr, C.getActiveOffloadKinds());
4640   }
4641 
4642   // If we are unable to embed a single device output into the host, we need to
4643   // add each device output as a host dependency to ensure they are still built.
4644   bool SingleDeviceOutput = !llvm::any_of(OffloadActions, [](Action *A) {
4645     return A->getType() == types::TY_Nothing;
4646   }) && isa<CompileJobAction>(HostAction);
4647   OffloadAction::HostDependence HDep(
4648       *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4649       /*BoundArch=*/nullptr, SingleDeviceOutput ? DDep : DDeps);
4650   return C.MakeAction<OffloadAction>(HDep, SingleDeviceOutput ? DDep : DDeps);
4651 }
4652 
4653 Action *Driver::ConstructPhaseAction(
4654     Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
4655     Action::OffloadKind TargetDeviceOffloadKind) const {
4656   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
4657 
4658   // Some types skip the assembler phase (e.g., llvm-bc), but we can't
4659   // encode this in the steps because the intermediate type depends on
4660   // arguments. Just special case here.
4661   if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
4662     return Input;
4663 
4664   // Build the appropriate action.
4665   switch (Phase) {
4666   case phases::Link:
4667     llvm_unreachable("link action invalid here.");
4668   case phases::IfsMerge:
4669     llvm_unreachable("ifsmerge action invalid here.");
4670   case phases::Preprocess: {
4671     types::ID OutputTy;
4672     // -M and -MM specify the dependency file name by altering the output type,
4673     // -if -MD and -MMD are not specified.
4674     if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
4675         !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
4676       OutputTy = types::TY_Dependencies;
4677     } else {
4678       OutputTy = Input->getType();
4679       // For these cases, the preprocessor is only translating forms, the Output
4680       // still needs preprocessing.
4681       if (!Args.hasFlag(options::OPT_frewrite_includes,
4682                         options::OPT_fno_rewrite_includes, false) &&
4683           !Args.hasFlag(options::OPT_frewrite_imports,
4684                         options::OPT_fno_rewrite_imports, false) &&
4685           !Args.hasFlag(options::OPT_fdirectives_only,
4686                         options::OPT_fno_directives_only, false) &&
4687           !CCGenDiagnostics)
4688         OutputTy = types::getPreprocessedType(OutputTy);
4689       assert(OutputTy != types::TY_INVALID &&
4690              "Cannot preprocess this input type!");
4691     }
4692     return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
4693   }
4694   case phases::Precompile: {
4695     // API extraction should not generate an actual precompilation action.
4696     if (Args.hasArg(options::OPT_extract_api))
4697       return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4698 
4699     types::ID OutputTy = getPrecompiledType(Input->getType());
4700     assert(OutputTy != types::TY_INVALID &&
4701            "Cannot precompile this input type!");
4702 
4703     // If we're given a module name, precompile header file inputs as a
4704     // module, not as a precompiled header.
4705     const char *ModName = nullptr;
4706     if (OutputTy == types::TY_PCH) {
4707       if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
4708         ModName = A->getValue();
4709       if (ModName)
4710         OutputTy = types::TY_ModuleFile;
4711     }
4712 
4713     if (Args.hasArg(options::OPT_fsyntax_only)) {
4714       // Syntax checks should not emit a PCH file
4715       OutputTy = types::TY_Nothing;
4716     }
4717 
4718     return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
4719   }
4720   case phases::Compile: {
4721     if (Args.hasArg(options::OPT_fsyntax_only))
4722       return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
4723     if (Args.hasArg(options::OPT_rewrite_objc))
4724       return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
4725     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
4726       return C.MakeAction<CompileJobAction>(Input,
4727                                             types::TY_RewrittenLegacyObjC);
4728     if (Args.hasArg(options::OPT__analyze))
4729       return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
4730     if (Args.hasArg(options::OPT__migrate))
4731       return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
4732     if (Args.hasArg(options::OPT_emit_ast))
4733       return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
4734     if (Args.hasArg(options::OPT_module_file_info))
4735       return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
4736     if (Args.hasArg(options::OPT_verify_pch))
4737       return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
4738     if (Args.hasArg(options::OPT_extract_api))
4739       return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4740     return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
4741   }
4742   case phases::Backend: {
4743     if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
4744       types::ID Output =
4745           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
4746       return C.MakeAction<BackendJobAction>(Input, Output);
4747     }
4748     if (isUsingLTO(/* IsOffload */ true) &&
4749         TargetDeviceOffloadKind != Action::OFK_None) {
4750       types::ID Output =
4751           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
4752       return C.MakeAction<BackendJobAction>(Input, Output);
4753     }
4754     if (Args.hasArg(options::OPT_emit_llvm) ||
4755         (((Input->getOffloadingToolChain() &&
4756            Input->getOffloadingToolChain()->getTriple().isAMDGPU()) ||
4757           TargetDeviceOffloadKind == Action::OFK_HIP) &&
4758          (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4759                        false) ||
4760           TargetDeviceOffloadKind == Action::OFK_OpenMP))) {
4761       types::ID Output =
4762           Args.hasArg(options::OPT_S) &&
4763                   (TargetDeviceOffloadKind == Action::OFK_None ||
4764                    offloadDeviceOnly() ||
4765                    (TargetDeviceOffloadKind == Action::OFK_HIP &&
4766                     !Args.hasFlag(options::OPT_offload_new_driver,
4767                                   options::OPT_no_offload_new_driver, false)))
4768               ? types::TY_LLVM_IR
4769               : types::TY_LLVM_BC;
4770       return C.MakeAction<BackendJobAction>(Input, Output);
4771     }
4772     return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
4773   }
4774   case phases::Assemble:
4775     return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
4776   }
4777 
4778   llvm_unreachable("invalid phase in ConstructPhaseAction");
4779 }
4780 
4781 void Driver::BuildJobs(Compilation &C) const {
4782   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4783 
4784   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4785 
4786   // It is an error to provide a -o option if we are making multiple output
4787   // files. There are exceptions:
4788   //
4789   // IfsMergeJob: when generating interface stubs enabled we want to be able to
4790   // generate the stub file at the same time that we generate the real
4791   // library/a.out. So when a .o, .so, etc are the output, with clang interface
4792   // stubs there will also be a .ifs and .ifso at the same location.
4793   //
4794   // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
4795   // and -c is passed, we still want to be able to generate a .ifs file while
4796   // we are also generating .o files. So we allow more than one output file in
4797   // this case as well.
4798   //
4799   // OffloadClass of type TY_Nothing: device-only output will place many outputs
4800   // into a single offloading action. We should count all inputs to the action
4801   // as outputs. Also ignore device-only outputs if we're compiling with
4802   // -fsyntax-only.
4803   if (FinalOutput) {
4804     unsigned NumOutputs = 0;
4805     unsigned NumIfsOutputs = 0;
4806     for (const Action *A : C.getActions()) {
4807       if (A->getType() != types::TY_Nothing &&
4808           A->getType() != types::TY_DX_CONTAINER &&
4809           !(A->getKind() == Action::IfsMergeJobClass ||
4810             (A->getType() == clang::driver::types::TY_IFS_CPP &&
4811              A->getKind() == clang::driver::Action::CompileJobClass &&
4812              0 == NumIfsOutputs++) ||
4813             (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
4814              A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
4815         ++NumOutputs;
4816       else if (A->getKind() == Action::OffloadClass &&
4817                A->getType() == types::TY_Nothing &&
4818                !C.getArgs().hasArg(options::OPT_fsyntax_only))
4819         NumOutputs += A->size();
4820     }
4821 
4822     if (NumOutputs > 1) {
4823       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
4824       FinalOutput = nullptr;
4825     }
4826   }
4827 
4828   const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
4829 
4830   // Collect the list of architectures.
4831   llvm::StringSet<> ArchNames;
4832   if (RawTriple.isOSBinFormatMachO())
4833     for (const Arg *A : C.getArgs())
4834       if (A->getOption().matches(options::OPT_arch))
4835         ArchNames.insert(A->getValue());
4836 
4837   // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
4838   std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults;
4839   for (Action *A : C.getActions()) {
4840     // If we are linking an image for multiple archs then the linker wants
4841     // -arch_multiple and -final_output <final image name>. Unfortunately, this
4842     // doesn't fit in cleanly because we have to pass this information down.
4843     //
4844     // FIXME: This is a hack; find a cleaner way to integrate this into the
4845     // process.
4846     const char *LinkingOutput = nullptr;
4847     if (isa<LipoJobAction>(A)) {
4848       if (FinalOutput)
4849         LinkingOutput = FinalOutput->getValue();
4850       else
4851         LinkingOutput = getDefaultImageName();
4852     }
4853 
4854     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
4855                        /*BoundArch*/ StringRef(),
4856                        /*AtTopLevel*/ true,
4857                        /*MultipleArchs*/ ArchNames.size() > 1,
4858                        /*LinkingOutput*/ LinkingOutput, CachedResults,
4859                        /*TargetDeviceOffloadKind*/ Action::OFK_None);
4860   }
4861 
4862   // If we have more than one job, then disable integrated-cc1 for now. Do this
4863   // also when we need to report process execution statistics.
4864   if (C.getJobs().size() > 1 || CCPrintProcessStats)
4865     for (auto &J : C.getJobs())
4866       J.InProcess = false;
4867 
4868   if (CCPrintProcessStats) {
4869     C.setPostCallback([=](const Command &Cmd, int Res) {
4870       std::optional<llvm::sys::ProcessStatistics> ProcStat =
4871           Cmd.getProcessStatistics();
4872       if (!ProcStat)
4873         return;
4874 
4875       const char *LinkingOutput = nullptr;
4876       if (FinalOutput)
4877         LinkingOutput = FinalOutput->getValue();
4878       else if (!Cmd.getOutputFilenames().empty())
4879         LinkingOutput = Cmd.getOutputFilenames().front().c_str();
4880       else
4881         LinkingOutput = getDefaultImageName();
4882 
4883       if (CCPrintStatReportFilename.empty()) {
4884         using namespace llvm;
4885         // Human readable output.
4886         outs() << sys::path::filename(Cmd.getExecutable()) << ": "
4887                << "output=" << LinkingOutput;
4888         outs() << ", total="
4889                << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
4890                << ", user="
4891                << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
4892                << ", mem=" << ProcStat->PeakMemory << " Kb\n";
4893       } else {
4894         // CSV format.
4895         std::string Buffer;
4896         llvm::raw_string_ostream Out(Buffer);
4897         llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
4898                             /*Quote*/ true);
4899         Out << ',';
4900         llvm::sys::printArg(Out, LinkingOutput, true);
4901         Out << ',' << ProcStat->TotalTime.count() << ','
4902             << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
4903             << '\n';
4904         Out.flush();
4905         std::error_code EC;
4906         llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC,
4907                                 llvm::sys::fs::OF_Append |
4908                                     llvm::sys::fs::OF_Text);
4909         if (EC)
4910           return;
4911         auto L = OS.lock();
4912         if (!L) {
4913           llvm::errs() << "ERROR: Cannot lock file "
4914                        << CCPrintStatReportFilename << ": "
4915                        << toString(L.takeError()) << "\n";
4916           return;
4917         }
4918         OS << Buffer;
4919         OS.flush();
4920       }
4921     });
4922   }
4923 
4924   // If the user passed -Qunused-arguments or there were errors, don't warn
4925   // about any unused arguments.
4926   if (Diags.hasErrorOccurred() ||
4927       C.getArgs().hasArg(options::OPT_Qunused_arguments))
4928     return;
4929 
4930   // Claim -fdriver-only here.
4931   (void)C.getArgs().hasArg(options::OPT_fdriver_only);
4932   // Claim -### here.
4933   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
4934 
4935   // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4936   (void)C.getArgs().hasArg(options::OPT_driver_mode);
4937   (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
4938 
4939   bool HasAssembleJob = llvm::any_of(C.getJobs(), [](auto &J) {
4940     // Match ClangAs and other derived assemblers of Tool. ClangAs uses a
4941     // longer ShortName "clang integrated assembler" while other assemblers just
4942     // use "assembler".
4943     return strstr(J.getCreator().getShortName(), "assembler");
4944   });
4945   for (Arg *A : C.getArgs()) {
4946     // FIXME: It would be nice to be able to send the argument to the
4947     // DiagnosticsEngine, so that extra values, position, and so on could be
4948     // printed.
4949     if (!A->isClaimed()) {
4950       if (A->getOption().hasFlag(options::NoArgumentUnused))
4951         continue;
4952 
4953       // Suppress the warning automatically if this is just a flag, and it is an
4954       // instance of an argument we already claimed.
4955       const Option &Opt = A->getOption();
4956       if (Opt.getKind() == Option::FlagClass) {
4957         bool DuplicateClaimed = false;
4958 
4959         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
4960           if (AA->isClaimed()) {
4961             DuplicateClaimed = true;
4962             break;
4963           }
4964         }
4965 
4966         if (DuplicateClaimed)
4967           continue;
4968       }
4969 
4970       // In clang-cl, don't mention unknown arguments here since they have
4971       // already been warned about.
4972       if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) {
4973         if (A->getOption().hasFlag(options::TargetSpecific) &&
4974             !A->isIgnoredTargetSpecific() && !HasAssembleJob) {
4975           Diag(diag::err_drv_unsupported_opt_for_target)
4976               << A->getSpelling() << getTargetTriple();
4977         } else {
4978           Diag(clang::diag::warn_drv_unused_argument)
4979               << A->getAsString(C.getArgs());
4980         }
4981       }
4982     }
4983   }
4984 }
4985 
4986 namespace {
4987 /// Utility class to control the collapse of dependent actions and select the
4988 /// tools accordingly.
4989 class ToolSelector final {
4990   /// The tool chain this selector refers to.
4991   const ToolChain &TC;
4992 
4993   /// The compilation this selector refers to.
4994   const Compilation &C;
4995 
4996   /// The base action this selector refers to.
4997   const JobAction *BaseAction;
4998 
4999   /// Set to true if the current toolchain refers to host actions.
5000   bool IsHostSelector;
5001 
5002   /// Set to true if save-temps and embed-bitcode functionalities are active.
5003   bool SaveTemps;
5004   bool EmbedBitcode;
5005 
5006   /// Get previous dependent action or null if that does not exist. If
5007   /// \a CanBeCollapsed is false, that action must be legal to collapse or
5008   /// null will be returned.
5009   const JobAction *getPrevDependentAction(const ActionList &Inputs,
5010                                           ActionList &SavedOffloadAction,
5011                                           bool CanBeCollapsed = true) {
5012     // An option can be collapsed only if it has a single input.
5013     if (Inputs.size() != 1)
5014       return nullptr;
5015 
5016     Action *CurAction = *Inputs.begin();
5017     if (CanBeCollapsed &&
5018         !CurAction->isCollapsingWithNextDependentActionLegal())
5019       return nullptr;
5020 
5021     // If the input action is an offload action. Look through it and save any
5022     // offload action that can be dropped in the event of a collapse.
5023     if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
5024       // If the dependent action is a device action, we will attempt to collapse
5025       // only with other device actions. Otherwise, we would do the same but
5026       // with host actions only.
5027       if (!IsHostSelector) {
5028         if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
5029           CurAction =
5030               OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
5031           if (CanBeCollapsed &&
5032               !CurAction->isCollapsingWithNextDependentActionLegal())
5033             return nullptr;
5034           SavedOffloadAction.push_back(OA);
5035           return dyn_cast<JobAction>(CurAction);
5036         }
5037       } else if (OA->hasHostDependence()) {
5038         CurAction = OA->getHostDependence();
5039         if (CanBeCollapsed &&
5040             !CurAction->isCollapsingWithNextDependentActionLegal())
5041           return nullptr;
5042         SavedOffloadAction.push_back(OA);
5043         return dyn_cast<JobAction>(CurAction);
5044       }
5045       return nullptr;
5046     }
5047 
5048     return dyn_cast<JobAction>(CurAction);
5049   }
5050 
5051   /// Return true if an assemble action can be collapsed.
5052   bool canCollapseAssembleAction() const {
5053     return TC.useIntegratedAs() && !SaveTemps &&
5054            !C.getArgs().hasArg(options::OPT_via_file_asm) &&
5055            !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
5056            !C.getArgs().hasArg(options::OPT__SLASH_Fa);
5057   }
5058 
5059   /// Return true if a preprocessor action can be collapsed.
5060   bool canCollapsePreprocessorAction() const {
5061     return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
5062            !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
5063            !C.getArgs().hasArg(options::OPT_rewrite_objc);
5064   }
5065 
5066   /// Struct that relates an action with the offload actions that would be
5067   /// collapsed with it.
5068   struct JobActionInfo final {
5069     /// The action this info refers to.
5070     const JobAction *JA = nullptr;
5071     /// The offload actions we need to take care off if this action is
5072     /// collapsed.
5073     ActionList SavedOffloadAction;
5074   };
5075 
5076   /// Append collapsed offload actions from the give nnumber of elements in the
5077   /// action info array.
5078   static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
5079                                            ArrayRef<JobActionInfo> &ActionInfo,
5080                                            unsigned ElementNum) {
5081     assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
5082     for (unsigned I = 0; I < ElementNum; ++I)
5083       CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
5084                                     ActionInfo[I].SavedOffloadAction.end());
5085   }
5086 
5087   /// Functions that attempt to perform the combining. They detect if that is
5088   /// legal, and if so they update the inputs \a Inputs and the offload action
5089   /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
5090   /// the combined action is returned. If the combining is not legal or if the
5091   /// tool does not exist, null is returned.
5092   /// Currently three kinds of collapsing are supported:
5093   ///  - Assemble + Backend + Compile;
5094   ///  - Assemble + Backend ;
5095   ///  - Backend + Compile.
5096   const Tool *
5097   combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
5098                                 ActionList &Inputs,
5099                                 ActionList &CollapsedOffloadAction) {
5100     if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
5101       return nullptr;
5102     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
5103     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
5104     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
5105     if (!AJ || !BJ || !CJ)
5106       return nullptr;
5107 
5108     // Get compiler tool.
5109     const Tool *T = TC.SelectTool(*CJ);
5110     if (!T)
5111       return nullptr;
5112 
5113     // Can't collapse if we don't have codegen support unless we are
5114     // emitting LLVM IR.
5115     bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
5116     if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
5117       return nullptr;
5118 
5119     // When using -fembed-bitcode, it is required to have the same tool (clang)
5120     // for both CompilerJA and BackendJA. Otherwise, combine two stages.
5121     if (EmbedBitcode) {
5122       const Tool *BT = TC.SelectTool(*BJ);
5123       if (BT == T)
5124         return nullptr;
5125     }
5126 
5127     if (!T->hasIntegratedAssembler())
5128       return nullptr;
5129 
5130     Inputs = CJ->getInputs();
5131     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5132                                  /*NumElements=*/3);
5133     return T;
5134   }
5135   const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
5136                                      ActionList &Inputs,
5137                                      ActionList &CollapsedOffloadAction) {
5138     if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
5139       return nullptr;
5140     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
5141     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
5142     if (!AJ || !BJ)
5143       return nullptr;
5144 
5145     // Get backend tool.
5146     const Tool *T = TC.SelectTool(*BJ);
5147     if (!T)
5148       return nullptr;
5149 
5150     if (!T->hasIntegratedAssembler())
5151       return nullptr;
5152 
5153     Inputs = BJ->getInputs();
5154     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5155                                  /*NumElements=*/2);
5156     return T;
5157   }
5158   const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
5159                                     ActionList &Inputs,
5160                                     ActionList &CollapsedOffloadAction) {
5161     if (ActionInfo.size() < 2)
5162       return nullptr;
5163     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
5164     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
5165     if (!BJ || !CJ)
5166       return nullptr;
5167 
5168     // Check if the initial input (to the compile job or its predessor if one
5169     // exists) is LLVM bitcode. In that case, no preprocessor step is required
5170     // and we can still collapse the compile and backend jobs when we have
5171     // -save-temps. I.e. there is no need for a separate compile job just to
5172     // emit unoptimized bitcode.
5173     bool InputIsBitcode = true;
5174     for (size_t i = 1; i < ActionInfo.size(); i++)
5175       if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
5176           ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
5177         InputIsBitcode = false;
5178         break;
5179       }
5180     if (!InputIsBitcode && !canCollapsePreprocessorAction())
5181       return nullptr;
5182 
5183     // Get compiler tool.
5184     const Tool *T = TC.SelectTool(*CJ);
5185     if (!T)
5186       return nullptr;
5187 
5188     // Can't collapse if we don't have codegen support unless we are
5189     // emitting LLVM IR.
5190     bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
5191     if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
5192       return nullptr;
5193 
5194     if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
5195       return nullptr;
5196 
5197     Inputs = CJ->getInputs();
5198     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5199                                  /*NumElements=*/2);
5200     return T;
5201   }
5202 
5203   /// Updates the inputs if the obtained tool supports combining with
5204   /// preprocessor action, and the current input is indeed a preprocessor
5205   /// action. If combining results in the collapse of offloading actions, those
5206   /// are appended to \a CollapsedOffloadAction.
5207   void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
5208                                ActionList &CollapsedOffloadAction) {
5209     if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
5210       return;
5211 
5212     // Attempt to get a preprocessor action dependence.
5213     ActionList PreprocessJobOffloadActions;
5214     ActionList NewInputs;
5215     for (Action *A : Inputs) {
5216       auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
5217       if (!PJ || !isa<PreprocessJobAction>(PJ)) {
5218         NewInputs.push_back(A);
5219         continue;
5220       }
5221 
5222       // This is legal to combine. Append any offload action we found and add the
5223       // current input to preprocessor inputs.
5224       CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
5225                                     PreprocessJobOffloadActions.end());
5226       NewInputs.append(PJ->input_begin(), PJ->input_end());
5227     }
5228     Inputs = NewInputs;
5229   }
5230 
5231 public:
5232   ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
5233                const Compilation &C, bool SaveTemps, bool EmbedBitcode)
5234       : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
5235         EmbedBitcode(EmbedBitcode) {
5236     assert(BaseAction && "Invalid base action.");
5237     IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
5238   }
5239 
5240   /// Check if a chain of actions can be combined and return the tool that can
5241   /// handle the combination of actions. The pointer to the current inputs \a
5242   /// Inputs and the list of offload actions \a CollapsedOffloadActions
5243   /// connected to collapsed actions are updated accordingly. The latter enables
5244   /// the caller of the selector to process them afterwards instead of just
5245   /// dropping them. If no suitable tool is found, null will be returned.
5246   const Tool *getTool(ActionList &Inputs,
5247                       ActionList &CollapsedOffloadAction) {
5248     //
5249     // Get the largest chain of actions that we could combine.
5250     //
5251 
5252     SmallVector<JobActionInfo, 5> ActionChain(1);
5253     ActionChain.back().JA = BaseAction;
5254     while (ActionChain.back().JA) {
5255       const Action *CurAction = ActionChain.back().JA;
5256 
5257       // Grow the chain by one element.
5258       ActionChain.resize(ActionChain.size() + 1);
5259       JobActionInfo &AI = ActionChain.back();
5260 
5261       // Attempt to fill it with the
5262       AI.JA =
5263           getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
5264     }
5265 
5266     // Pop the last action info as it could not be filled.
5267     ActionChain.pop_back();
5268 
5269     //
5270     // Attempt to combine actions. If all combining attempts failed, just return
5271     // the tool of the provided action. At the end we attempt to combine the
5272     // action with any preprocessor action it may depend on.
5273     //
5274 
5275     const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
5276                                                   CollapsedOffloadAction);
5277     if (!T)
5278       T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
5279     if (!T)
5280       T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
5281     if (!T) {
5282       Inputs = BaseAction->getInputs();
5283       T = TC.SelectTool(*BaseAction);
5284     }
5285 
5286     combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
5287     return T;
5288   }
5289 };
5290 }
5291 
5292 /// Return a string that uniquely identifies the result of a job. The bound arch
5293 /// is not necessarily represented in the toolchain's triple -- for example,
5294 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
5295 /// Also, we need to add the offloading device kind, as the same tool chain can
5296 /// be used for host and device for some programming models, e.g. OpenMP.
5297 static std::string GetTriplePlusArchString(const ToolChain *TC,
5298                                            StringRef BoundArch,
5299                                            Action::OffloadKind OffloadKind) {
5300   std::string TriplePlusArch = TC->getTriple().normalize();
5301   if (!BoundArch.empty()) {
5302     TriplePlusArch += "-";
5303     TriplePlusArch += BoundArch;
5304   }
5305   TriplePlusArch += "-";
5306   TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
5307   return TriplePlusArch;
5308 }
5309 
5310 InputInfoList Driver::BuildJobsForAction(
5311     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
5312     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5313     std::map<std::pair<const Action *, std::string>, InputInfoList>
5314         &CachedResults,
5315     Action::OffloadKind TargetDeviceOffloadKind) const {
5316   std::pair<const Action *, std::string> ActionTC = {
5317       A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5318   auto CachedResult = CachedResults.find(ActionTC);
5319   if (CachedResult != CachedResults.end()) {
5320     return CachedResult->second;
5321   }
5322   InputInfoList Result = BuildJobsForActionNoCache(
5323       C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
5324       CachedResults, TargetDeviceOffloadKind);
5325   CachedResults[ActionTC] = Result;
5326   return Result;
5327 }
5328 
5329 static void handleTimeTrace(Compilation &C, const ArgList &Args,
5330                             const JobAction *JA, const char *BaseInput,
5331                             const InputInfo &Result) {
5332   Arg *A =
5333       Args.getLastArg(options::OPT_ftime_trace, options::OPT_ftime_trace_EQ);
5334   if (!A)
5335     return;
5336   SmallString<128> Path;
5337   if (A->getOption().matches(options::OPT_ftime_trace_EQ)) {
5338     Path = A->getValue();
5339     if (llvm::sys::fs::is_directory(Path)) {
5340       SmallString<128> Tmp(Result.getFilename());
5341       llvm::sys::path::replace_extension(Tmp, "json");
5342       llvm::sys::path::append(Path, llvm::sys::path::filename(Tmp));
5343     }
5344   } else {
5345     if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
5346       // The trace file is ${dumpdir}${basename}.json. Note that dumpdir may not
5347       // end with a path separator.
5348       Path = DumpDir->getValue();
5349       Path += llvm::sys::path::filename(BaseInput);
5350     } else {
5351       Path = Result.getFilename();
5352     }
5353     llvm::sys::path::replace_extension(Path, "json");
5354   }
5355   const char *ResultFile = C.getArgs().MakeArgString(Path);
5356   C.addTimeTraceFile(ResultFile, JA);
5357   C.addResultFile(ResultFile, JA);
5358 }
5359 
5360 InputInfoList Driver::BuildJobsForActionNoCache(
5361     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
5362     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5363     std::map<std::pair<const Action *, std::string>, InputInfoList>
5364         &CachedResults,
5365     Action::OffloadKind TargetDeviceOffloadKind) const {
5366   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
5367 
5368   InputInfoList OffloadDependencesInputInfo;
5369   bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
5370   if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
5371     // The 'Darwin' toolchain is initialized only when its arguments are
5372     // computed. Get the default arguments for OFK_None to ensure that
5373     // initialization is performed before processing the offload action.
5374     // FIXME: Remove when darwin's toolchain is initialized during construction.
5375     C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
5376 
5377     // The offload action is expected to be used in four different situations.
5378     //
5379     // a) Set a toolchain/architecture/kind for a host action:
5380     //    Host Action 1 -> OffloadAction -> Host Action 2
5381     //
5382     // b) Set a toolchain/architecture/kind for a device action;
5383     //    Device Action 1 -> OffloadAction -> Device Action 2
5384     //
5385     // c) Specify a device dependence to a host action;
5386     //    Device Action 1  _
5387     //                      \
5388     //      Host Action 1  ---> OffloadAction -> Host Action 2
5389     //
5390     // d) Specify a host dependence to a device action.
5391     //      Host Action 1  _
5392     //                      \
5393     //    Device Action 1  ---> OffloadAction -> Device Action 2
5394     //
5395     // For a) and b), we just return the job generated for the dependences. For
5396     // c) and d) we override the current action with the host/device dependence
5397     // if the current toolchain is host/device and set the offload dependences
5398     // info with the jobs obtained from the device/host dependence(s).
5399 
5400     // If there is a single device option or has no host action, just generate
5401     // the job for it.
5402     if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
5403       InputInfoList DevA;
5404       OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
5405                                        const char *DepBoundArch) {
5406         DevA.append(BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
5407                                        /*MultipleArchs*/ !!DepBoundArch,
5408                                        LinkingOutput, CachedResults,
5409                                        DepA->getOffloadingDeviceKind()));
5410       });
5411       return DevA;
5412     }
5413 
5414     // If 'Action 2' is host, we generate jobs for the device dependences and
5415     // override the current action with the host dependence. Otherwise, we
5416     // generate the host dependences and override the action with the device
5417     // dependence. The dependences can't therefore be a top-level action.
5418     OA->doOnEachDependence(
5419         /*IsHostDependence=*/BuildingForOffloadDevice,
5420         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
5421           OffloadDependencesInputInfo.append(BuildJobsForAction(
5422               C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
5423               /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
5424               DepA->getOffloadingDeviceKind()));
5425         });
5426 
5427     A = BuildingForOffloadDevice
5428             ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
5429             : OA->getHostDependence();
5430 
5431     // We may have already built this action as a part of the offloading
5432     // toolchain, return the cached input if so.
5433     std::pair<const Action *, std::string> ActionTC = {
5434         OA->getHostDependence(),
5435         GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5436     if (CachedResults.find(ActionTC) != CachedResults.end()) {
5437       InputInfoList Inputs = CachedResults[ActionTC];
5438       Inputs.append(OffloadDependencesInputInfo);
5439       return Inputs;
5440     }
5441   }
5442 
5443   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
5444     // FIXME: It would be nice to not claim this here; maybe the old scheme of
5445     // just using Args was better?
5446     const Arg &Input = IA->getInputArg();
5447     Input.claim();
5448     if (Input.getOption().matches(options::OPT_INPUT)) {
5449       const char *Name = Input.getValue();
5450       return {InputInfo(A, Name, /* _BaseInput = */ Name)};
5451     }
5452     return {InputInfo(A, &Input, /* _BaseInput = */ "")};
5453   }
5454 
5455   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
5456     const ToolChain *TC;
5457     StringRef ArchName = BAA->getArchName();
5458 
5459     if (!ArchName.empty())
5460       TC = &getToolChain(C.getArgs(),
5461                          computeTargetTriple(*this, TargetTriple,
5462                                              C.getArgs(), ArchName));
5463     else
5464       TC = &C.getDefaultToolChain();
5465 
5466     return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
5467                               MultipleArchs, LinkingOutput, CachedResults,
5468                               TargetDeviceOffloadKind);
5469   }
5470 
5471 
5472   ActionList Inputs = A->getInputs();
5473 
5474   const JobAction *JA = cast<JobAction>(A);
5475   ActionList CollapsedOffloadActions;
5476 
5477   ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
5478                   embedBitcodeInObject() && !isUsingLTO());
5479   const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
5480 
5481   if (!T)
5482     return {InputInfo()};
5483 
5484   // If we've collapsed action list that contained OffloadAction we
5485   // need to build jobs for host/device-side inputs it may have held.
5486   for (const auto *OA : CollapsedOffloadActions)
5487     cast<OffloadAction>(OA)->doOnEachDependence(
5488         /*IsHostDependence=*/BuildingForOffloadDevice,
5489         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
5490           OffloadDependencesInputInfo.append(BuildJobsForAction(
5491               C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
5492               /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
5493               DepA->getOffloadingDeviceKind()));
5494         });
5495 
5496   // Only use pipes when there is exactly one input.
5497   InputInfoList InputInfos;
5498   for (const Action *Input : Inputs) {
5499     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
5500     // shouldn't get temporary output names.
5501     // FIXME: Clean this up.
5502     bool SubJobAtTopLevel =
5503         AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
5504     InputInfos.append(BuildJobsForAction(
5505         C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
5506         CachedResults, A->getOffloadingDeviceKind()));
5507   }
5508 
5509   // Always use the first file input as the base input.
5510   const char *BaseInput = InputInfos[0].getBaseInput();
5511   for (auto &Info : InputInfos) {
5512     if (Info.isFilename()) {
5513       BaseInput = Info.getBaseInput();
5514       break;
5515     }
5516   }
5517 
5518   // ... except dsymutil actions, which use their actual input as the base
5519   // input.
5520   if (JA->getType() == types::TY_dSYM)
5521     BaseInput = InputInfos[0].getFilename();
5522 
5523   // Append outputs of offload device jobs to the input list
5524   if (!OffloadDependencesInputInfo.empty())
5525     InputInfos.append(OffloadDependencesInputInfo.begin(),
5526                       OffloadDependencesInputInfo.end());
5527 
5528   // Set the effective triple of the toolchain for the duration of this job.
5529   llvm::Triple EffectiveTriple;
5530   const ToolChain &ToolTC = T->getToolChain();
5531   const ArgList &Args =
5532       C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
5533   if (InputInfos.size() != 1) {
5534     EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
5535   } else {
5536     // Pass along the input type if it can be unambiguously determined.
5537     EffectiveTriple = llvm::Triple(
5538         ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
5539   }
5540   RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
5541 
5542   // Determine the place to write output to, if any.
5543   InputInfo Result;
5544   InputInfoList UnbundlingResults;
5545   if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
5546     // If we have an unbundling job, we need to create results for all the
5547     // outputs. We also update the results cache so that other actions using
5548     // this unbundling action can get the right results.
5549     for (auto &UI : UA->getDependentActionsInfo()) {
5550       assert(UI.DependentOffloadKind != Action::OFK_None &&
5551              "Unbundling with no offloading??");
5552 
5553       // Unbundling actions are never at the top level. When we generate the
5554       // offloading prefix, we also do that for the host file because the
5555       // unbundling action does not change the type of the output which can
5556       // cause a overwrite.
5557       std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5558           UI.DependentOffloadKind,
5559           UI.DependentToolChain->getTriple().normalize(),
5560           /*CreatePrefixForHost=*/true);
5561       auto CurI = InputInfo(
5562           UA,
5563           GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
5564                              /*AtTopLevel=*/false,
5565                              MultipleArchs ||
5566                                  UI.DependentOffloadKind == Action::OFK_HIP,
5567                              OffloadingPrefix),
5568           BaseInput);
5569       // Save the unbundling result.
5570       UnbundlingResults.push_back(CurI);
5571 
5572       // Get the unique string identifier for this dependence and cache the
5573       // result.
5574       StringRef Arch;
5575       if (TargetDeviceOffloadKind == Action::OFK_HIP) {
5576         if (UI.DependentOffloadKind == Action::OFK_Host)
5577           Arch = StringRef();
5578         else
5579           Arch = UI.DependentBoundArch;
5580       } else
5581         Arch = BoundArch;
5582 
5583       CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
5584                                                 UI.DependentOffloadKind)}] = {
5585           CurI};
5586     }
5587 
5588     // Now that we have all the results generated, select the one that should be
5589     // returned for the current depending action.
5590     std::pair<const Action *, std::string> ActionTC = {
5591         A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5592     assert(CachedResults.find(ActionTC) != CachedResults.end() &&
5593            "Result does not exist??");
5594     Result = CachedResults[ActionTC].front();
5595   } else if (JA->getType() == types::TY_Nothing)
5596     Result = {InputInfo(A, BaseInput)};
5597   else {
5598     // We only have to generate a prefix for the host if this is not a top-level
5599     // action.
5600     std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5601         A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
5602         /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(A) ||
5603             !(A->getOffloadingHostActiveKinds() == Action::OFK_None ||
5604               AtTopLevel));
5605     Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
5606                                              AtTopLevel, MultipleArchs,
5607                                              OffloadingPrefix),
5608                        BaseInput);
5609     if (T->canEmitIR() && OffloadingPrefix.empty())
5610       handleTimeTrace(C, Args, JA, BaseInput, Result);
5611   }
5612 
5613   if (CCCPrintBindings && !CCGenDiagnostics) {
5614     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
5615                  << " - \"" << T->getName() << "\", inputs: [";
5616     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
5617       llvm::errs() << InputInfos[i].getAsString();
5618       if (i + 1 != e)
5619         llvm::errs() << ", ";
5620     }
5621     if (UnbundlingResults.empty())
5622       llvm::errs() << "], output: " << Result.getAsString() << "\n";
5623     else {
5624       llvm::errs() << "], outputs: [";
5625       for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
5626         llvm::errs() << UnbundlingResults[i].getAsString();
5627         if (i + 1 != e)
5628           llvm::errs() << ", ";
5629       }
5630       llvm::errs() << "] \n";
5631     }
5632   } else {
5633     if (UnbundlingResults.empty())
5634       T->ConstructJob(
5635           C, *JA, Result, InputInfos,
5636           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5637           LinkingOutput);
5638     else
5639       T->ConstructJobMultipleOutputs(
5640           C, *JA, UnbundlingResults, InputInfos,
5641           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5642           LinkingOutput);
5643   }
5644   return {Result};
5645 }
5646 
5647 const char *Driver::getDefaultImageName() const {
5648   llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
5649   return Target.isOSWindows() ? "a.exe" : "a.out";
5650 }
5651 
5652 /// Create output filename based on ArgValue, which could either be a
5653 /// full filename, filename without extension, or a directory. If ArgValue
5654 /// does not provide a filename, then use BaseName, and use the extension
5655 /// suitable for FileType.
5656 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
5657                                         StringRef BaseName,
5658                                         types::ID FileType) {
5659   SmallString<128> Filename = ArgValue;
5660 
5661   if (ArgValue.empty()) {
5662     // If the argument is empty, output to BaseName in the current dir.
5663     Filename = BaseName;
5664   } else if (llvm::sys::path::is_separator(Filename.back())) {
5665     // If the argument is a directory, output to BaseName in that dir.
5666     llvm::sys::path::append(Filename, BaseName);
5667   }
5668 
5669   if (!llvm::sys::path::has_extension(ArgValue)) {
5670     // If the argument didn't provide an extension, then set it.
5671     const char *Extension = types::getTypeTempSuffix(FileType, true);
5672 
5673     if (FileType == types::TY_Image &&
5674         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
5675       // The output file is a dll.
5676       Extension = "dll";
5677     }
5678 
5679     llvm::sys::path::replace_extension(Filename, Extension);
5680   }
5681 
5682   return Args.MakeArgString(Filename.c_str());
5683 }
5684 
5685 static bool HasPreprocessOutput(const Action &JA) {
5686   if (isa<PreprocessJobAction>(JA))
5687     return true;
5688   if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0]))
5689     return true;
5690   if (isa<OffloadBundlingJobAction>(JA) &&
5691       HasPreprocessOutput(*(JA.getInputs()[0])))
5692     return true;
5693   return false;
5694 }
5695 
5696 const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix,
5697                                    StringRef Suffix, bool MultipleArchs,
5698                                    StringRef BoundArch,
5699                                    bool NeedUniqueDirectory) const {
5700   SmallString<128> TmpName;
5701   Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
5702   std::optional<std::string> CrashDirectory =
5703       CCGenDiagnostics && A
5704           ? std::string(A->getValue())
5705           : llvm::sys::Process::GetEnv("CLANG_CRASH_DIAGNOSTICS_DIR");
5706   if (CrashDirectory) {
5707     if (!getVFS().exists(*CrashDirectory))
5708       llvm::sys::fs::create_directories(*CrashDirectory);
5709     SmallString<128> Path(*CrashDirectory);
5710     llvm::sys::path::append(Path, Prefix);
5711     const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%";
5712     if (std::error_code EC =
5713             llvm::sys::fs::createUniqueFile(Path + Middle + Suffix, TmpName)) {
5714       Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5715       return "";
5716     }
5717   } else {
5718     if (MultipleArchs && !BoundArch.empty()) {
5719       if (NeedUniqueDirectory) {
5720         TmpName = GetTemporaryDirectory(Prefix);
5721         llvm::sys::path::append(TmpName,
5722                                 Twine(Prefix) + "-" + BoundArch + "." + Suffix);
5723       } else {
5724         TmpName =
5725             GetTemporaryPath((Twine(Prefix) + "-" + BoundArch).str(), Suffix);
5726       }
5727 
5728     } else {
5729       TmpName = GetTemporaryPath(Prefix, Suffix);
5730     }
5731   }
5732   return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5733 }
5734 
5735 // Calculate the output path of the module file when compiling a module unit
5736 // with the `-fmodule-output` option or `-fmodule-output=` option specified.
5737 // The behavior is:
5738 // - If `-fmodule-output=` is specfied, then the module file is
5739 //   writing to the value.
5740 // - Otherwise if the output object file of the module unit is specified, the
5741 // output path
5742 //   of the module file should be the same with the output object file except
5743 //   the corresponding suffix. This requires both `-o` and `-c` are specified.
5744 // - Otherwise, the output path of the module file will be the same with the
5745 //   input with the corresponding suffix.
5746 static const char *GetModuleOutputPath(Compilation &C, const JobAction &JA,
5747                                        const char *BaseInput) {
5748   assert(isa<PrecompileJobAction>(JA) && JA.getType() == types::TY_ModuleFile &&
5749          (C.getArgs().hasArg(options::OPT_fmodule_output) ||
5750           C.getArgs().hasArg(options::OPT_fmodule_output_EQ)));
5751 
5752   if (Arg *ModuleOutputEQ =
5753           C.getArgs().getLastArg(options::OPT_fmodule_output_EQ))
5754     return C.addResultFile(ModuleOutputEQ->getValue(), &JA);
5755 
5756   SmallString<64> OutputPath;
5757   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
5758   if (FinalOutput && C.getArgs().hasArg(options::OPT_c))
5759     OutputPath = FinalOutput->getValue();
5760   else
5761     OutputPath = BaseInput;
5762 
5763   const char *Extension = types::getTypeTempSuffix(JA.getType());
5764   llvm::sys::path::replace_extension(OutputPath, Extension);
5765   return C.addResultFile(C.getArgs().MakeArgString(OutputPath.c_str()), &JA);
5766 }
5767 
5768 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
5769                                        const char *BaseInput,
5770                                        StringRef OrigBoundArch, bool AtTopLevel,
5771                                        bool MultipleArchs,
5772                                        StringRef OffloadingPrefix) const {
5773   std::string BoundArch = OrigBoundArch.str();
5774   if (is_style_windows(llvm::sys::path::Style::native)) {
5775     // BoundArch may contains ':', which is invalid in file names on Windows,
5776     // therefore replace it with '%'.
5777     std::replace(BoundArch.begin(), BoundArch.end(), ':', '@');
5778   }
5779 
5780   llvm::PrettyStackTraceString CrashInfo("Computing output path");
5781   // Output to a user requested destination?
5782   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
5783     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
5784       return C.addResultFile(FinalOutput->getValue(), &JA);
5785   }
5786 
5787   // For /P, preprocess to file named after BaseInput.
5788   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
5789     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
5790     StringRef BaseName = llvm::sys::path::filename(BaseInput);
5791     StringRef NameArg;
5792     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
5793       NameArg = A->getValue();
5794     return C.addResultFile(
5795         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
5796         &JA);
5797   }
5798 
5799   // Default to writing to stdout?
5800   if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
5801     return "-";
5802   }
5803 
5804   if (JA.getType() == types::TY_ModuleFile &&
5805       C.getArgs().getLastArg(options::OPT_module_file_info)) {
5806     return "-";
5807   }
5808 
5809   if (IsDXCMode() && !C.getArgs().hasArg(options::OPT_o))
5810     return "-";
5811 
5812   // Is this the assembly listing for /FA?
5813   if (JA.getType() == types::TY_PP_Asm &&
5814       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
5815        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
5816     // Use /Fa and the input filename to determine the asm file name.
5817     StringRef BaseName = llvm::sys::path::filename(BaseInput);
5818     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
5819     return C.addResultFile(
5820         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
5821         &JA);
5822   }
5823 
5824   bool SpecifiedModuleOutput =
5825       C.getArgs().hasArg(options::OPT_fmodule_output) ||
5826       C.getArgs().hasArg(options::OPT_fmodule_output_EQ);
5827   if (MultipleArchs && SpecifiedModuleOutput)
5828     Diag(clang::diag::err_drv_module_output_with_multiple_arch);
5829 
5830   // If we're emitting a module output with the specified option
5831   // `-fmodule-output`.
5832   if (!AtTopLevel && isa<PrecompileJobAction>(JA) &&
5833       JA.getType() == types::TY_ModuleFile && SpecifiedModuleOutput)
5834     return GetModuleOutputPath(C, JA, BaseInput);
5835 
5836   // Output to a temporary file?
5837   if ((!AtTopLevel && !isSaveTempsEnabled() &&
5838        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
5839       CCGenDiagnostics) {
5840     StringRef Name = llvm::sys::path::filename(BaseInput);
5841     std::pair<StringRef, StringRef> Split = Name.split('.');
5842     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
5843     // The non-offloading toolchain on Darwin requires deterministic input
5844     // file name for binaries to be deterministic, therefore it needs unique
5845     // directory.
5846     llvm::Triple Triple(C.getDriver().getTargetTriple());
5847     bool NeedUniqueDirectory =
5848         (JA.getOffloadingDeviceKind() == Action::OFK_None ||
5849          JA.getOffloadingDeviceKind() == Action::OFK_Host) &&
5850         Triple.isOSDarwin();
5851     return CreateTempFile(C, Split.first, Suffix, MultipleArchs, BoundArch,
5852                           NeedUniqueDirectory);
5853   }
5854 
5855   SmallString<128> BasePath(BaseInput);
5856   SmallString<128> ExternalPath("");
5857   StringRef BaseName;
5858 
5859   // Dsymutil actions should use the full path.
5860   if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) {
5861     ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
5862     // We use posix style here because the tests (specifically
5863     // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
5864     // even on Windows and if we don't then the similar test covering this
5865     // fails.
5866     llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix,
5867                             llvm::sys::path::filename(BasePath));
5868     BaseName = ExternalPath;
5869   } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
5870     BaseName = BasePath;
5871   else
5872     BaseName = llvm::sys::path::filename(BasePath);
5873 
5874   // Determine what the derived output name should be.
5875   const char *NamedOutput;
5876 
5877   if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
5878       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
5879     // The /Fo or /o flag decides the object filename.
5880     StringRef Val =
5881         C.getArgs()
5882             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
5883             ->getValue();
5884     NamedOutput =
5885         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5886   } else if (JA.getType() == types::TY_Image &&
5887              C.getArgs().hasArg(options::OPT__SLASH_Fe,
5888                                 options::OPT__SLASH_o)) {
5889     // The /Fe or /o flag names the linked file.
5890     StringRef Val =
5891         C.getArgs()
5892             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
5893             ->getValue();
5894     NamedOutput =
5895         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
5896   } else if (JA.getType() == types::TY_Image) {
5897     if (IsCLMode()) {
5898       // clang-cl uses BaseName for the executable name.
5899       NamedOutput =
5900           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
5901     } else {
5902       SmallString<128> Output(getDefaultImageName());
5903       // HIP image for device compilation with -fno-gpu-rdc is per compilation
5904       // unit.
5905       bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5906                         !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
5907                                              options::OPT_fno_gpu_rdc, false);
5908       bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(JA);
5909       if (UseOutExtension) {
5910         Output = BaseName;
5911         llvm::sys::path::replace_extension(Output, "");
5912       }
5913       Output += OffloadingPrefix;
5914       if (MultipleArchs && !BoundArch.empty()) {
5915         Output += "-";
5916         Output.append(BoundArch);
5917       }
5918       if (UseOutExtension)
5919         Output += ".out";
5920       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
5921     }
5922   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
5923     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
5924   } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) &&
5925              C.getArgs().hasArg(options::OPT__SLASH_o)) {
5926     StringRef Val =
5927         C.getArgs()
5928             .getLastArg(options::OPT__SLASH_o)
5929             ->getValue();
5930     NamedOutput =
5931         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5932   } else {
5933     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
5934     assert(Suffix && "All types used for output should have a suffix.");
5935 
5936     std::string::size_type End = std::string::npos;
5937     if (!types::appendSuffixForType(JA.getType()))
5938       End = BaseName.rfind('.');
5939     SmallString<128> Suffixed(BaseName.substr(0, End));
5940     Suffixed += OffloadingPrefix;
5941     if (MultipleArchs && !BoundArch.empty()) {
5942       Suffixed += "-";
5943       Suffixed.append(BoundArch);
5944     }
5945     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
5946     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
5947     // optimized bitcode output.
5948     auto IsAMDRDCInCompilePhase = [](const JobAction &JA,
5949                                      const llvm::opt::DerivedArgList &Args) {
5950       // The relocatable compilation in HIP and OpenMP implies -emit-llvm.
5951       // Similarly, use a ".tmp.bc" suffix for the unoptimized bitcode
5952       // (generated in the compile phase.)
5953       const ToolChain *TC = JA.getOffloadingToolChain();
5954       return isa<CompileJobAction>(JA) &&
5955              ((JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5956                Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5957                             false)) ||
5958               (JA.getOffloadingDeviceKind() == Action::OFK_OpenMP && TC &&
5959                TC->getTriple().isAMDGPU()));
5960     };
5961     if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
5962         (C.getArgs().hasArg(options::OPT_emit_llvm) ||
5963          IsAMDRDCInCompilePhase(JA, C.getArgs())))
5964       Suffixed += ".tmp";
5965     Suffixed += '.';
5966     Suffixed += Suffix;
5967     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
5968   }
5969 
5970   // Prepend object file path if -save-temps=obj
5971   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
5972       JA.getType() != types::TY_PCH) {
5973     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
5974     SmallString<128> TempPath(FinalOutput->getValue());
5975     llvm::sys::path::remove_filename(TempPath);
5976     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
5977     llvm::sys::path::append(TempPath, OutputFileName);
5978     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
5979   }
5980 
5981   // If we're saving temps and the temp file conflicts with the input file,
5982   // then avoid overwriting input file.
5983   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
5984     bool SameFile = false;
5985     SmallString<256> Result;
5986     llvm::sys::fs::current_path(Result);
5987     llvm::sys::path::append(Result, BaseName);
5988     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
5989     // Must share the same path to conflict.
5990     if (SameFile) {
5991       StringRef Name = llvm::sys::path::filename(BaseInput);
5992       std::pair<StringRef, StringRef> Split = Name.split('.');
5993       std::string TmpName = GetTemporaryPath(
5994           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
5995       return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5996     }
5997   }
5998 
5999   // As an annoying special case, PCH generation doesn't strip the pathname.
6000   if (JA.getType() == types::TY_PCH && !IsCLMode()) {
6001     llvm::sys::path::remove_filename(BasePath);
6002     if (BasePath.empty())
6003       BasePath = NamedOutput;
6004     else
6005       llvm::sys::path::append(BasePath, NamedOutput);
6006     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
6007   }
6008 
6009   return C.addResultFile(NamedOutput, &JA);
6010 }
6011 
6012 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
6013   // Search for Name in a list of paths.
6014   auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
6015       -> std::optional<std::string> {
6016     // Respect a limited subset of the '-Bprefix' functionality in GCC by
6017     // attempting to use this prefix when looking for file paths.
6018     for (const auto &Dir : P) {
6019       if (Dir.empty())
6020         continue;
6021       SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
6022       llvm::sys::path::append(P, Name);
6023       if (llvm::sys::fs::exists(Twine(P)))
6024         return std::string(P);
6025     }
6026     return std::nullopt;
6027   };
6028 
6029   if (auto P = SearchPaths(PrefixDirs))
6030     return *P;
6031 
6032   SmallString<128> R(ResourceDir);
6033   llvm::sys::path::append(R, Name);
6034   if (llvm::sys::fs::exists(Twine(R)))
6035     return std::string(R.str());
6036 
6037   SmallString<128> P(TC.getCompilerRTPath());
6038   llvm::sys::path::append(P, Name);
6039   if (llvm::sys::fs::exists(Twine(P)))
6040     return std::string(P.str());
6041 
6042   SmallString<128> D(Dir);
6043   llvm::sys::path::append(D, "..", Name);
6044   if (llvm::sys::fs::exists(Twine(D)))
6045     return std::string(D.str());
6046 
6047   if (auto P = SearchPaths(TC.getLibraryPaths()))
6048     return *P;
6049 
6050   if (auto P = SearchPaths(TC.getFilePaths()))
6051     return *P;
6052 
6053   return std::string(Name);
6054 }
6055 
6056 void Driver::generatePrefixedToolNames(
6057     StringRef Tool, const ToolChain &TC,
6058     SmallVectorImpl<std::string> &Names) const {
6059   // FIXME: Needs a better variable than TargetTriple
6060   Names.emplace_back((TargetTriple + "-" + Tool).str());
6061   Names.emplace_back(Tool);
6062 }
6063 
6064 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
6065   llvm::sys::path::append(Dir, Name);
6066   if (llvm::sys::fs::can_execute(Twine(Dir)))
6067     return true;
6068   llvm::sys::path::remove_filename(Dir);
6069   return false;
6070 }
6071 
6072 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
6073   SmallVector<std::string, 2> TargetSpecificExecutables;
6074   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
6075 
6076   // Respect a limited subset of the '-Bprefix' functionality in GCC by
6077   // attempting to use this prefix when looking for program paths.
6078   for (const auto &PrefixDir : PrefixDirs) {
6079     if (llvm::sys::fs::is_directory(PrefixDir)) {
6080       SmallString<128> P(PrefixDir);
6081       if (ScanDirForExecutable(P, Name))
6082         return std::string(P.str());
6083     } else {
6084       SmallString<128> P((PrefixDir + Name).str());
6085       if (llvm::sys::fs::can_execute(Twine(P)))
6086         return std::string(P.str());
6087     }
6088   }
6089 
6090   const ToolChain::path_list &List = TC.getProgramPaths();
6091   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
6092     // For each possible name of the tool look for it in
6093     // program paths first, then the path.
6094     // Higher priority names will be first, meaning that
6095     // a higher priority name in the path will be found
6096     // instead of a lower priority name in the program path.
6097     // E.g. <triple>-gcc on the path will be found instead
6098     // of gcc in the program path
6099     for (const auto &Path : List) {
6100       SmallString<128> P(Path);
6101       if (ScanDirForExecutable(P, TargetSpecificExecutable))
6102         return std::string(P.str());
6103     }
6104 
6105     // Fall back to the path
6106     if (llvm::ErrorOr<std::string> P =
6107             llvm::sys::findProgramByName(TargetSpecificExecutable))
6108       return *P;
6109   }
6110 
6111   return std::string(Name);
6112 }
6113 
6114 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
6115   SmallString<128> Path;
6116   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
6117   if (EC) {
6118     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
6119     return "";
6120   }
6121 
6122   return std::string(Path.str());
6123 }
6124 
6125 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
6126   SmallString<128> Path;
6127   std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
6128   if (EC) {
6129     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
6130     return "";
6131   }
6132 
6133   return std::string(Path.str());
6134 }
6135 
6136 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
6137   SmallString<128> Output;
6138   if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
6139     // FIXME: If anybody needs it, implement this obscure rule:
6140     // "If you specify a directory without a file name, the default file name
6141     // is VCx0.pch., where x is the major version of Visual C++ in use."
6142     Output = FpArg->getValue();
6143 
6144     // "If you do not specify an extension as part of the path name, an
6145     // extension of .pch is assumed. "
6146     if (!llvm::sys::path::has_extension(Output))
6147       Output += ".pch";
6148   } else {
6149     if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
6150       Output = YcArg->getValue();
6151     if (Output.empty())
6152       Output = BaseName;
6153     llvm::sys::path::replace_extension(Output, ".pch");
6154   }
6155   return std::string(Output.str());
6156 }
6157 
6158 const ToolChain &Driver::getToolChain(const ArgList &Args,
6159                                       const llvm::Triple &Target) const {
6160 
6161   auto &TC = ToolChains[Target.str()];
6162   if (!TC) {
6163     switch (Target.getOS()) {
6164     case llvm::Triple::AIX:
6165       TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
6166       break;
6167     case llvm::Triple::Haiku:
6168       TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
6169       break;
6170     case llvm::Triple::Ananas:
6171       TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
6172       break;
6173     case llvm::Triple::CloudABI:
6174       TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
6175       break;
6176     case llvm::Triple::Darwin:
6177     case llvm::Triple::MacOSX:
6178     case llvm::Triple::IOS:
6179     case llvm::Triple::TvOS:
6180     case llvm::Triple::WatchOS:
6181     case llvm::Triple::DriverKit:
6182       TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
6183       break;
6184     case llvm::Triple::DragonFly:
6185       TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
6186       break;
6187     case llvm::Triple::OpenBSD:
6188       TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
6189       break;
6190     case llvm::Triple::NetBSD:
6191       TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
6192       break;
6193     case llvm::Triple::FreeBSD:
6194       if (Target.isPPC())
6195         TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target,
6196                                                                Args);
6197       else
6198         TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
6199       break;
6200     case llvm::Triple::Minix:
6201       TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
6202       break;
6203     case llvm::Triple::Linux:
6204     case llvm::Triple::ELFIAMCU:
6205       if (Target.getArch() == llvm::Triple::hexagon)
6206         TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
6207                                                              Args);
6208       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
6209                !Target.hasEnvironment())
6210         TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
6211                                                               Args);
6212       else if (Target.isPPC())
6213         TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
6214                                                               Args);
6215       else if (Target.getArch() == llvm::Triple::ve)
6216         TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
6217       else if (Target.isOHOSFamily())
6218         TC = std::make_unique<toolchains::OHOS>(*this, Target, Args);
6219       else
6220         TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
6221       break;
6222     case llvm::Triple::NaCl:
6223       TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
6224       break;
6225     case llvm::Triple::Fuchsia:
6226       TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
6227       break;
6228     case llvm::Triple::Solaris:
6229       TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
6230       break;
6231     case llvm::Triple::CUDA:
6232       TC = std::make_unique<toolchains::NVPTXToolChain>(*this, Target, Args);
6233       break;
6234     case llvm::Triple::AMDHSA:
6235       TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
6236       break;
6237     case llvm::Triple::AMDPAL:
6238     case llvm::Triple::Mesa3D:
6239       TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
6240       break;
6241     case llvm::Triple::Win32:
6242       switch (Target.getEnvironment()) {
6243       default:
6244         if (Target.isOSBinFormatELF())
6245           TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
6246         else if (Target.isOSBinFormatMachO())
6247           TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
6248         else
6249           TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
6250         break;
6251       case llvm::Triple::GNU:
6252         TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
6253         break;
6254       case llvm::Triple::Itanium:
6255         TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
6256                                                                   Args);
6257         break;
6258       case llvm::Triple::MSVC:
6259       case llvm::Triple::UnknownEnvironment:
6260         if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
6261                 .starts_with_insensitive("bfd"))
6262           TC = std::make_unique<toolchains::CrossWindowsToolChain>(
6263               *this, Target, Args);
6264         else
6265           TC =
6266               std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
6267         break;
6268       }
6269       break;
6270     case llvm::Triple::PS4:
6271       TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
6272       break;
6273     case llvm::Triple::PS5:
6274       TC = std::make_unique<toolchains::PS5CPU>(*this, Target, Args);
6275       break;
6276     case llvm::Triple::Contiki:
6277       TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
6278       break;
6279     case llvm::Triple::Hurd:
6280       TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
6281       break;
6282     case llvm::Triple::LiteOS:
6283       TC = std::make_unique<toolchains::OHOS>(*this, Target, Args);
6284       break;
6285     case llvm::Triple::ZOS:
6286       TC = std::make_unique<toolchains::ZOS>(*this, Target, Args);
6287       break;
6288     case llvm::Triple::ShaderModel:
6289       TC = std::make_unique<toolchains::HLSLToolChain>(*this, Target, Args);
6290       break;
6291     default:
6292       // Of these targets, Hexagon is the only one that might have
6293       // an OS of Linux, in which case it got handled above already.
6294       switch (Target.getArch()) {
6295       case llvm::Triple::tce:
6296         TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
6297         break;
6298       case llvm::Triple::tcele:
6299         TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
6300         break;
6301       case llvm::Triple::hexagon:
6302         TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
6303                                                              Args);
6304         break;
6305       case llvm::Triple::lanai:
6306         TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
6307         break;
6308       case llvm::Triple::xcore:
6309         TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
6310         break;
6311       case llvm::Triple::wasm32:
6312       case llvm::Triple::wasm64:
6313         TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
6314         break;
6315       case llvm::Triple::avr:
6316         TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
6317         break;
6318       case llvm::Triple::msp430:
6319         TC =
6320             std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
6321         break;
6322       case llvm::Triple::riscv32:
6323       case llvm::Triple::riscv64:
6324         if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
6325           TC =
6326               std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
6327         else
6328           TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
6329         break;
6330       case llvm::Triple::ve:
6331         TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
6332         break;
6333       case llvm::Triple::spirv32:
6334       case llvm::Triple::spirv64:
6335         TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args);
6336         break;
6337       case llvm::Triple::csky:
6338         TC = std::make_unique<toolchains::CSKYToolChain>(*this, Target, Args);
6339         break;
6340       default:
6341         if (Target.getVendor() == llvm::Triple::Myriad)
6342           TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
6343                                                               Args);
6344         else if (toolchains::BareMetal::handlesTarget(Target))
6345           TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
6346         else if (Target.isOSBinFormatELF())
6347           TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
6348         else if (Target.isOSBinFormatMachO())
6349           TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
6350         else
6351           TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
6352       }
6353     }
6354   }
6355 
6356   return *TC;
6357 }
6358 
6359 const ToolChain &Driver::getOffloadingDeviceToolChain(
6360     const ArgList &Args, const llvm::Triple &Target, const ToolChain &HostTC,
6361     const Action::OffloadKind &TargetDeviceOffloadKind) const {
6362   // Use device / host triples as the key into the ToolChains map because the
6363   // device ToolChain we create depends on both.
6364   auto &TC = ToolChains[Target.str() + "/" + HostTC.getTriple().str()];
6365   if (!TC) {
6366     // Categorized by offload kind > arch rather than OS > arch like
6367     // the normal getToolChain call, as it seems a reasonable way to categorize
6368     // things.
6369     switch (TargetDeviceOffloadKind) {
6370     case Action::OFK_HIP: {
6371       if (Target.getArch() == llvm::Triple::amdgcn &&
6372           Target.getVendor() == llvm::Triple::AMD &&
6373           Target.getOS() == llvm::Triple::AMDHSA)
6374         TC = std::make_unique<toolchains::HIPAMDToolChain>(*this, Target,
6375                                                            HostTC, Args);
6376       else if (Target.getArch() == llvm::Triple::spirv64 &&
6377                Target.getVendor() == llvm::Triple::UnknownVendor &&
6378                Target.getOS() == llvm::Triple::UnknownOS)
6379         TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target,
6380                                                            HostTC, Args);
6381       break;
6382     }
6383     default:
6384       break;
6385     }
6386   }
6387 
6388   return *TC;
6389 }
6390 
6391 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
6392   // Say "no" if there is not exactly one input of a type clang understands.
6393   if (JA.size() != 1 ||
6394       !types::isAcceptedByClang((*JA.input_begin())->getType()))
6395     return false;
6396 
6397   // And say "no" if this is not a kind of action clang understands.
6398   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
6399       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA) &&
6400       !isa<ExtractAPIJobAction>(JA))
6401     return false;
6402 
6403   return true;
6404 }
6405 
6406 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
6407   // Say "no" if there is not exactly one input of a type flang understands.
6408   if (JA.size() != 1 ||
6409       !types::isAcceptedByFlang((*JA.input_begin())->getType()))
6410     return false;
6411 
6412   // And say "no" if this is not a kind of action flang understands.
6413   if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) &&
6414       !isa<BackendJobAction>(JA))
6415     return false;
6416 
6417   return true;
6418 }
6419 
6420 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
6421   // Only emit static library if the flag is set explicitly.
6422   if (Args.hasArg(options::OPT_emit_static_lib))
6423     return true;
6424   return false;
6425 }
6426 
6427 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
6428 /// grouped values as integers. Numbers which are not provided are set to 0.
6429 ///
6430 /// \return True if the entire string was parsed (9.2), or all groups were
6431 /// parsed (10.3.5extrastuff).
6432 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
6433                                unsigned &Micro, bool &HadExtra) {
6434   HadExtra = false;
6435 
6436   Major = Minor = Micro = 0;
6437   if (Str.empty())
6438     return false;
6439 
6440   if (Str.consumeInteger(10, Major))
6441     return false;
6442   if (Str.empty())
6443     return true;
6444   if (Str[0] != '.')
6445     return false;
6446 
6447   Str = Str.drop_front(1);
6448 
6449   if (Str.consumeInteger(10, Minor))
6450     return false;
6451   if (Str.empty())
6452     return true;
6453   if (Str[0] != '.')
6454     return false;
6455   Str = Str.drop_front(1);
6456 
6457   if (Str.consumeInteger(10, Micro))
6458     return false;
6459   if (!Str.empty())
6460     HadExtra = true;
6461   return true;
6462 }
6463 
6464 /// Parse digits from a string \p Str and fulfill \p Digits with
6465 /// the parsed numbers. This method assumes that the max number of
6466 /// digits to look for is equal to Digits.size().
6467 ///
6468 /// \return True if the entire string was parsed and there are
6469 /// no extra characters remaining at the end.
6470 bool Driver::GetReleaseVersion(StringRef Str,
6471                                MutableArrayRef<unsigned> Digits) {
6472   if (Str.empty())
6473     return false;
6474 
6475   unsigned CurDigit = 0;
6476   while (CurDigit < Digits.size()) {
6477     unsigned Digit;
6478     if (Str.consumeInteger(10, Digit))
6479       return false;
6480     Digits[CurDigit] = Digit;
6481     if (Str.empty())
6482       return true;
6483     if (Str[0] != '.')
6484       return false;
6485     Str = Str.drop_front(1);
6486     CurDigit++;
6487   }
6488 
6489   // More digits than requested, bail out...
6490   return false;
6491 }
6492 
6493 std::pair<unsigned, unsigned>
6494 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
6495   unsigned IncludedFlagsBitmask = 0;
6496   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
6497 
6498   if (IsClCompatMode) {
6499     // Include CL and Core options.
6500     IncludedFlagsBitmask |= options::CLOption;
6501     IncludedFlagsBitmask |= options::CLDXCOption;
6502     IncludedFlagsBitmask |= options::CoreOption;
6503   } else {
6504     ExcludedFlagsBitmask |= options::CLOption;
6505   }
6506   if (IsDXCMode()) {
6507     // Include DXC and Core options.
6508     IncludedFlagsBitmask |= options::DXCOption;
6509     IncludedFlagsBitmask |= options::CLDXCOption;
6510     IncludedFlagsBitmask |= options::CoreOption;
6511   } else {
6512     ExcludedFlagsBitmask |= options::DXCOption;
6513   }
6514   if (!IsClCompatMode && !IsDXCMode())
6515     ExcludedFlagsBitmask |= options::CLDXCOption;
6516 
6517   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
6518 }
6519 
6520 const char *Driver::getExecutableForDriverMode(DriverMode Mode) {
6521   switch (Mode) {
6522   case GCCMode:
6523     return "clang";
6524   case GXXMode:
6525     return "clang++";
6526   case CPPMode:
6527     return "clang-cpp";
6528   case CLMode:
6529     return "clang-cl";
6530   case FlangMode:
6531     return "flang";
6532   case DXCMode:
6533     return "clang-dxc";
6534   }
6535 
6536   llvm_unreachable("Unhandled Mode");
6537 }
6538 
6539 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
6540   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
6541 }
6542 
6543 bool clang::driver::willEmitRemarks(const ArgList &Args) {
6544   // -fsave-optimization-record enables it.
6545   if (Args.hasFlag(options::OPT_fsave_optimization_record,
6546                    options::OPT_fno_save_optimization_record, false))
6547     return true;
6548 
6549   // -fsave-optimization-record=<format> enables it as well.
6550   if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
6551                    options::OPT_fno_save_optimization_record, false))
6552     return true;
6553 
6554   // -foptimization-record-file alone enables it too.
6555   if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
6556                    options::OPT_fno_save_optimization_record, false))
6557     return true;
6558 
6559   // -foptimization-record-passes alone enables it too.
6560   if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
6561                    options::OPT_fno_save_optimization_record, false))
6562     return true;
6563   return false;
6564 }
6565 
6566 llvm::StringRef clang::driver::getDriverMode(StringRef ProgName,
6567                                              ArrayRef<const char *> Args) {
6568   static const std::string OptName =
6569       getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName();
6570   llvm::StringRef Opt;
6571   for (StringRef Arg : Args) {
6572     if (!Arg.startswith(OptName))
6573       continue;
6574     Opt = Arg;
6575   }
6576   if (Opt.empty())
6577     Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode;
6578   return Opt.consume_front(OptName) ? Opt : "";
6579 }
6580 
6581 bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); }
6582 
6583 llvm::Error driver::expandResponseFiles(SmallVectorImpl<const char *> &Args,
6584                                         bool ClangCLMode,
6585                                         llvm::BumpPtrAllocator &Alloc,
6586                                         llvm::vfs::FileSystem *FS) {
6587   // Parse response files using the GNU syntax, unless we're in CL mode. There
6588   // are two ways to put clang in CL compatibility mode: ProgName is either
6589   // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
6590   // command line parsing can't happen until after response file parsing, so we
6591   // have to manually search for a --driver-mode=cl argument the hard way.
6592   // Finally, our -cc1 tools don't care which tokenization mode we use because
6593   // response files written by clang will tokenize the same way in either mode.
6594   enum { Default, POSIX, Windows } RSPQuoting = Default;
6595   for (const char *F : Args) {
6596     if (strcmp(F, "--rsp-quoting=posix") == 0)
6597       RSPQuoting = POSIX;
6598     else if (strcmp(F, "--rsp-quoting=windows") == 0)
6599       RSPQuoting = Windows;
6600   }
6601 
6602   // Determines whether we want nullptr markers in Args to indicate response
6603   // files end-of-lines. We only use this for the /LINK driver argument with
6604   // clang-cl.exe on Windows.
6605   bool MarkEOLs = ClangCLMode;
6606 
6607   llvm::cl::TokenizerCallback Tokenizer;
6608   if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode))
6609     Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
6610   else
6611     Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
6612 
6613   if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).startswith("-cc1"))
6614     MarkEOLs = false;
6615 
6616   llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
6617   ECtx.setMarkEOLs(MarkEOLs);
6618   if (FS)
6619     ECtx.setVFS(FS);
6620 
6621   if (llvm::Error Err = ECtx.expandResponseFiles(Args))
6622     return Err;
6623 
6624   // If -cc1 came from a response file, remove the EOL sentinels.
6625   auto FirstArg = llvm::find_if(llvm::drop_begin(Args),
6626                                 [](const char *A) { return A != nullptr; });
6627   if (FirstArg != Args.end() && StringRef(*FirstArg).startswith("-cc1")) {
6628     // If -cc1 came from a response file, remove the EOL sentinels.
6629     if (MarkEOLs) {
6630       auto newEnd = std::remove(Args.begin(), Args.end(), nullptr);
6631       Args.resize(newEnd - Args.begin());
6632     }
6633   }
6634 
6635   return llvm::Error::success();
6636 }
6637