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