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