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