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