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