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