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