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