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