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