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