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