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