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