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