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