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

source code of clang/lib/Driver/Driver.cpp