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