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