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