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