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