1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Driver/Driver.h"
11 #include "InputInfo.h"
12 #include "ToolChains/AMDGPU.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/BareMetal.h"
16 #include "ToolChains/Clang.h"
17 #include "ToolChains/CloudABI.h"
18 #include "ToolChains/Contiki.h"
19 #include "ToolChains/CrossWindows.h"
20 #include "ToolChains/Cuda.h"
21 #include "ToolChains/Darwin.h"
22 #include "ToolChains/DragonFly.h"
23 #include "ToolChains/FreeBSD.h"
24 #include "ToolChains/Fuchsia.h"
25 #include "ToolChains/Gnu.h"
26 #include "ToolChains/HIP.h"
27 #include "ToolChains/Haiku.h"
28 #include "ToolChains/Hexagon.h"
29 #include "ToolChains/Hurd.h"
30 #include "ToolChains/Lanai.h"
31 #include "ToolChains/Linux.h"
32 #include "ToolChains/MSP430.h"
33 #include "ToolChains/MSVC.h"
34 #include "ToolChains/MinGW.h"
35 #include "ToolChains/Minix.h"
36 #include "ToolChains/MipsLinux.h"
37 #include "ToolChains/Myriad.h"
38 #include "ToolChains/NaCl.h"
39 #include "ToolChains/NetBSD.h"
40 #include "ToolChains/OpenBSD.h"
41 #include "ToolChains/PS4CPU.h"
42 #include "ToolChains/RISCVToolchain.h"
43 #include "ToolChains/Solaris.h"
44 #include "ToolChains/TCE.h"
45 #include "ToolChains/WebAssembly.h"
46 #include "ToolChains/XCore.h"
47 #include "clang/Basic/Version.h"
48 #include "clang/Config/config.h"
49 #include "clang/Driver/Action.h"
50 #include "clang/Driver/Compilation.h"
51 #include "clang/Driver/DriverDiagnostic.h"
52 #include "clang/Driver/Job.h"
53 #include "clang/Driver/Options.h"
54 #include "clang/Driver/SanitizerArgs.h"
55 #include "clang/Driver/Tool.h"
56 #include "clang/Driver/ToolChain.h"
57 #include "llvm/ADT/ArrayRef.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include "llvm/ADT/SmallSet.h"
60 #include "llvm/ADT/StringExtras.h"
61 #include "llvm/ADT/StringSet.h"
62 #include "llvm/ADT/StringSwitch.h"
63 #include "llvm/Config/llvm-config.h"
64 #include "llvm/Option/Arg.h"
65 #include "llvm/Option/ArgList.h"
66 #include "llvm/Option/OptSpecifier.h"
67 #include "llvm/Option/OptTable.h"
68 #include "llvm/Option/Option.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/FileSystem.h"
72 #include "llvm/Support/FormatVariadic.h"
73 #include "llvm/Support/Path.h"
74 #include "llvm/Support/PrettyStackTrace.h"
75 #include "llvm/Support/Process.h"
76 #include "llvm/Support/Program.h"
77 #include "llvm/Support/StringSaver.h"
78 #include "llvm/Support/TargetRegistry.h"
79 #include "llvm/Support/VirtualFileSystem.h"
80 #include "llvm/Support/raw_ostream.h"
85 #include <unistd.h> // getpid
86 #include <sysexits.h> // EX_IOERR
89 using namespace clang::driver;
90 using namespace clang;
91 using namespace llvm::opt;
93 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
94 DiagnosticsEngine &Diags,
95 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
96 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
97 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
98 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
99 SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
100 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
101 CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
102 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
103 CCGenDiagnostics(false), TargetTriple(TargetTriple),
104 CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
105 GenReproducer(false), SuppressMissingInputWarning(false) {
107 // Provide a sane fallback if no VFS is specified.
109 this->VFS = llvm::vfs::getRealFileSystem();
111 Name = llvm::sys::path::filename(ClangExecutable);
112 Dir = llvm::sys::path::parent_path(ClangExecutable);
113 InstalledDir = Dir; // Provide a sensible default installed dir.
115 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
116 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
118 #if defined(CLANG_CONFIG_FILE_USER_DIR)
119 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
122 // Compute the path to the resource directory.
123 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
124 SmallString<128> P(Dir);
125 if (ClangResourceDir != "") {
126 llvm::sys::path::append(P, ClangResourceDir);
128 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
129 P = llvm::sys::path::parent_path(Dir);
130 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
131 CLANG_VERSION_STRING);
133 ResourceDir = P.str();
136 void Driver::ParseDriverMode(StringRef ProgramName,
137 ArrayRef<const char *> Args) {
138 if (ClangNameParts.isEmpty())
139 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
140 setDriverModeFromOption(ClangNameParts.DriverMode);
142 for (const char *ArgPtr : Args) {
143 // Ignore nullptrs, they are the response file's EOL markers.
144 if (ArgPtr == nullptr)
146 const StringRef Arg = ArgPtr;
147 setDriverModeFromOption(Arg);
151 void Driver::setDriverModeFromOption(StringRef Opt) {
152 const std::string OptName =
153 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
154 if (!Opt.startswith(OptName))
156 StringRef Value = Opt.drop_front(OptName.size());
158 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
159 .Case("gcc", GCCMode)
160 .Case("g++", GXXMode)
161 .Case("cpp", CPPMode)
166 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
169 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
171 bool &ContainsError) {
172 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
173 ContainsError = false;
175 unsigned IncludedFlagsBitmask;
176 unsigned ExcludedFlagsBitmask;
177 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
178 getIncludeExcludeOptionFlagMasks(IsClCompatMode);
180 unsigned MissingArgIndex, MissingArgCount;
182 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
183 IncludedFlagsBitmask, ExcludedFlagsBitmask);
185 // Check for missing argument error.
186 if (MissingArgCount) {
187 Diag(diag::err_drv_missing_argument)
188 << Args.getArgString(MissingArgIndex) << MissingArgCount;
190 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
191 SourceLocation()) > DiagnosticsEngine::Warning;
194 // Check for unsupported options.
195 for (const Arg *A : Args) {
196 if (A->getOption().hasFlag(options::Unsupported)) {
198 auto ArgString = A->getAsString(Args);
200 if (getOpts().findNearest(
201 ArgString, Nearest, IncludedFlagsBitmask,
202 ExcludedFlagsBitmask | options::Unsupported) > 1) {
203 DiagID = diag::err_drv_unsupported_opt;
204 Diag(DiagID) << ArgString;
206 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
207 Diag(DiagID) << ArgString << Nearest;
209 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
210 DiagnosticsEngine::Warning;
214 // Warn about -mcpu= without an argument.
215 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
216 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
217 ContainsError |= Diags.getDiagnosticLevel(
218 diag::warn_drv_empty_joined_argument,
219 SourceLocation()) > DiagnosticsEngine::Warning;
223 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
225 auto ArgString = A->getAsString(Args);
227 if (getOpts().findNearest(
228 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
229 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
230 : diag::err_drv_unknown_argument;
231 Diags.Report(DiagID) << ArgString;
233 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
234 : diag::err_drv_unknown_argument_with_suggestion;
235 Diags.Report(DiagID) << ArgString << Nearest;
237 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
238 DiagnosticsEngine::Warning;
244 // Determine which compilation mode we are in. We look for options which
245 // affect the phase, starting with the earliest phases, and record which
246 // option we used to determine the final phase.
247 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
248 Arg **FinalPhaseArg) const {
249 Arg *PhaseArg = nullptr;
250 phases::ID FinalPhase;
252 // -{E,EP,P,M,MM} only run the preprocessor.
253 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
254 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
255 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
256 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
257 FinalPhase = phases::Preprocess;
259 // --precompile only runs up to precompilation.
260 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
261 FinalPhase = phases::Precompile;
263 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
264 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
265 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
266 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
267 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
268 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
269 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
270 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
271 options::OPT__analyze_auto)) ||
272 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
273 FinalPhase = phases::Compile;
275 // -S only runs up to the backend.
276 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
277 FinalPhase = phases::Backend;
279 // -c compilation only runs up to the assembler.
280 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
281 FinalPhase = phases::Assemble;
283 // Otherwise do everything.
285 FinalPhase = phases::Link;
288 *FinalPhaseArg = PhaseArg;
293 static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
294 StringRef Value, bool Claim = true) {
295 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
296 Args.getBaseArgs().MakeIndex(Value), Value.data());
297 Args.AddSynthesizedArg(A);
303 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
304 DerivedArgList *DAL = new DerivedArgList(Args);
306 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
307 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
308 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
309 for (Arg *A : Args) {
310 // Unfortunately, we have to parse some forwarding options (-Xassembler,
311 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
312 // (assembler and preprocessor), or bypass a previous driver ('collect2').
314 // Rewrite linker options, to replace --no-demangle with a custom internal
316 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
317 A->getOption().matches(options::OPT_Xlinker)) &&
318 A->containsValue("--no-demangle")) {
319 // Add the rewritten no-demangle argument.
320 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
322 // Add the remaining values as Xlinker arguments.
323 for (StringRef Val : A->getValues())
324 if (Val != "--no-demangle")
325 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
330 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
331 // some build systems. We don't try to be complete here because we don't
332 // care to encourage this usage model.
333 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
334 (A->getValue(0) == StringRef("-MD") ||
335 A->getValue(0) == StringRef("-MMD"))) {
336 // Rewrite to -MD/-MMD along with -MF.
337 if (A->getValue(0) == StringRef("-MD"))
338 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
340 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
341 if (A->getNumValues() == 2)
342 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
347 // Rewrite reserved library names.
348 if (A->getOption().matches(options::OPT_l)) {
349 StringRef Value = A->getValue();
351 // Rewrite unless -nostdlib is present.
352 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
354 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
358 // Rewrite unconditionally.
359 if (Value == "cc_kext") {
360 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
365 // Pick up inputs via the -- option.
366 if (A->getOption().matches(options::OPT__DASH_DASH)) {
368 for (StringRef Val : A->getValues())
369 DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
376 // Enforce -static if -miamcu is present.
377 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
378 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
380 // Add a default value of -mlinker-version=, if one was given and the user
381 // didn't specify one.
382 #if defined(HOST_LINK_VERSION)
383 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
384 strlen(HOST_LINK_VERSION) > 0) {
385 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
387 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
394 /// Compute target triple from args.
396 /// This routine provides the logic to compute a target triple from various
397 /// args passed to the driver and the default triple string.
398 static llvm::Triple computeTargetTriple(const Driver &D,
399 StringRef TargetTriple,
401 StringRef DarwinArchName = "") {
402 // FIXME: Already done in Compilation *Driver::BuildCompilation
403 if (const Arg *A = Args.getLastArg(options::OPT_target))
404 TargetTriple = A->getValue();
406 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
408 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
409 // -gnu* only, and we can not change this, so we have to detect that case as
410 // being the Hurd OS.
411 if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
412 TargetTriple.find("-pc-gnu") != StringRef::npos)
413 Target.setOSName("hurd");
415 // Handle Apple-specific options available here.
416 if (Target.isOSBinFormatMachO()) {
417 // If an explicit Darwin arch name is given, that trumps all.
418 if (!DarwinArchName.empty()) {
419 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
423 // Handle the Darwin '-arch' flag.
424 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
425 StringRef ArchName = A->getValue();
426 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
430 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
431 // '-mbig-endian'/'-EB'.
432 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
433 options::OPT_mbig_endian)) {
434 if (A->getOption().matches(options::OPT_mlittle_endian)) {
435 llvm::Triple LE = Target.getLittleEndianArchVariant();
436 if (LE.getArch() != llvm::Triple::UnknownArch)
437 Target = std::move(LE);
439 llvm::Triple BE = Target.getBigEndianArchVariant();
440 if (BE.getArch() != llvm::Triple::UnknownArch)
441 Target = std::move(BE);
445 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
446 if (Target.getArch() == llvm::Triple::tce ||
447 Target.getOS() == llvm::Triple::Minix)
450 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
451 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
452 options::OPT_m32, options::OPT_m16);
454 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
456 if (A->getOption().matches(options::OPT_m64)) {
457 AT = Target.get64BitArchVariant().getArch();
458 if (Target.getEnvironment() == llvm::Triple::GNUX32)
459 Target.setEnvironment(llvm::Triple::GNU);
460 } else if (A->getOption().matches(options::OPT_mx32) &&
461 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
462 AT = llvm::Triple::x86_64;
463 Target.setEnvironment(llvm::Triple::GNUX32);
464 } else if (A->getOption().matches(options::OPT_m32)) {
465 AT = Target.get32BitArchVariant().getArch();
466 if (Target.getEnvironment() == llvm::Triple::GNUX32)
467 Target.setEnvironment(llvm::Triple::GNU);
468 } else if (A->getOption().matches(options::OPT_m16) &&
469 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
470 AT = llvm::Triple::x86;
471 Target.setEnvironment(llvm::Triple::CODE16);
474 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
478 // Handle -miamcu flag.
479 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
480 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
481 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
484 if (A && !A->getOption().matches(options::OPT_m32))
485 D.Diag(diag::err_drv_argument_not_allowed_with)
486 << "-miamcu" << A->getBaseArg().getAsString(Args);
488 Target.setArch(llvm::Triple::x86);
489 Target.setArchName("i586");
490 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
491 Target.setEnvironmentName("");
492 Target.setOS(llvm::Triple::ELFIAMCU);
493 Target.setVendor(llvm::Triple::UnknownVendor);
494 Target.setVendorName("intel");
497 // If target is MIPS adjust the target triple
498 // accordingly to provided ABI name.
499 A = Args.getLastArg(options::OPT_mabi_EQ);
500 if (A && Target.isMIPS()) {
501 StringRef ABIName = A->getValue();
502 if (ABIName == "32") {
503 Target = Target.get32BitArchVariant();
504 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
505 Target.getEnvironment() == llvm::Triple::GNUABIN32)
506 Target.setEnvironment(llvm::Triple::GNU);
507 } else if (ABIName == "n32") {
508 Target = Target.get64BitArchVariant();
509 if (Target.getEnvironment() == llvm::Triple::GNU ||
510 Target.getEnvironment() == llvm::Triple::GNUABI64)
511 Target.setEnvironment(llvm::Triple::GNUABIN32);
512 } else if (ABIName == "64") {
513 Target = Target.get64BitArchVariant();
514 if (Target.getEnvironment() == llvm::Triple::GNU ||
515 Target.getEnvironment() == llvm::Triple::GNUABIN32)
516 Target.setEnvironment(llvm::Triple::GNUABI64);
523 // Parse the LTO options and record the type of LTO compilation
524 // based on which -f(no-)?lto(=.*)? option occurs last.
525 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
527 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
528 options::OPT_fno_lto, false))
531 StringRef LTOName("full");
533 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
535 LTOName = A->getValue();
537 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
538 .Case("full", LTOK_Full)
539 .Case("thin", LTOK_Thin)
540 .Default(LTOK_Unknown);
542 if (LTOMode == LTOK_Unknown) {
544 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
549 /// Compute the desired OpenMP runtime from the flags provided.
550 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
551 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
553 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
555 RuntimeName = A->getValue();
557 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
558 .Case("libomp", OMPRT_OMP)
559 .Case("libgomp", OMPRT_GOMP)
560 .Case("libiomp5", OMPRT_IOMP5)
561 .Default(OMPRT_Unknown);
563 if (RT == OMPRT_Unknown) {
565 Diag(diag::err_drv_unsupported_option_argument)
566 << A->getOption().getName() << A->getValue();
568 // FIXME: We could use a nicer diagnostic here.
569 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
575 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
581 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
582 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
584 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
585 return types::isCuda(I.first);
589 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
590 return types::isHIP(I.first);
592 C.getInputArgs().hasArg(options::OPT_hip_link);
593 if (IsCuda && IsHIP) {
594 Diag(clang::diag::err_drv_mix_cuda_hip);
598 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
599 const llvm::Triple &HostTriple = HostTC->getTriple();
600 StringRef DeviceTripleStr;
601 auto OFK = Action::OFK_Cuda;
603 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
604 llvm::Triple CudaTriple(DeviceTripleStr);
605 // Use the CUDA and host triples as the key into the ToolChains map,
606 // because the device toolchain we create depends on both.
607 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
609 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
610 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
612 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
614 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
615 const llvm::Triple &HostTriple = HostTC->getTriple();
616 StringRef DeviceTripleStr;
617 auto OFK = Action::OFK_HIP;
618 DeviceTripleStr = "amdgcn-amd-amdhsa";
619 llvm::Triple HIPTriple(DeviceTripleStr);
620 // Use the HIP and host triples as the key into the ToolChains map,
621 // because the device toolchain we create depends on both.
622 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
624 HIPTC = llvm::make_unique<toolchains::HIPToolChain>(
625 *this, HIPTriple, *HostTC, C.getInputArgs());
627 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
633 // We need to generate an OpenMP toolchain if the user specified targets with
634 // the -fopenmp-targets option.
635 if (Arg *OpenMPTargets =
636 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
637 if (OpenMPTargets->getNumValues()) {
638 // We expect that -fopenmp-targets is always used in conjunction with the
639 // option -fopenmp specifying a valid runtime with offloading support,
640 // i.e. libomp or libiomp.
641 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
642 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
643 options::OPT_fno_openmp, false);
644 if (HasValidOpenMPRuntime) {
645 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
646 HasValidOpenMPRuntime =
647 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
650 if (HasValidOpenMPRuntime) {
651 llvm::StringMap<const char *> FoundNormalizedTriples;
652 for (const char *Val : OpenMPTargets->getValues()) {
653 llvm::Triple TT(Val);
654 std::string NormalizedName = TT.normalize();
656 // Make sure we don't have a duplicate triple.
657 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
658 if (Duplicate != FoundNormalizedTriples.end()) {
659 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
660 << Val << Duplicate->second;
664 // Store the current triple so that we can check for duplicates in the
665 // following iterations.
666 FoundNormalizedTriples[NormalizedName] = Val;
668 // If the specified target is invalid, emit a diagnostic.
669 if (TT.getArch() == llvm::Triple::UnknownArch)
670 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
673 // CUDA toolchains have to be selected differently. They pair host
674 // and device in their implementation.
676 const ToolChain *HostTC =
677 C.getSingleOffloadToolChain<Action::OFK_Host>();
678 assert(HostTC && "Host toolchain should be always defined.");
680 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
682 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
683 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
686 TC = &getToolChain(C.getInputArgs(), TT);
687 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
691 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
693 Diag(clang::diag::warn_drv_empty_joined_argument)
694 << OpenMPTargets->getAsString(C.getInputArgs());
698 // TODO: Add support for other offloading programming models here.
702 /// Looks the given directories for the specified file.
704 /// \param[out] FilePath File path, if the file was found.
705 /// \param[in] Dirs Directories used for the search.
706 /// \param[in] FileName Name of the file to search for.
707 /// \return True if file was found.
709 /// Looks for file specified by FileName sequentially in directories specified
712 static bool searchForFile(SmallVectorImpl<char> &FilePath,
713 ArrayRef<std::string> Dirs,
714 StringRef FileName) {
715 SmallString<128> WPath;
716 for (const StringRef &Dir : Dirs) {
720 llvm::sys::path::append(WPath, Dir, FileName);
721 llvm::sys::path::native(WPath);
722 if (llvm::sys::fs::is_regular_file(WPath)) {
723 FilePath = std::move(WPath);
730 bool Driver::readConfigFile(StringRef FileName) {
731 // Try reading the given file.
732 SmallVector<const char *, 32> NewCfgArgs;
733 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
734 Diag(diag::err_drv_cannot_read_config_file) << FileName;
738 // Read options from config file.
739 llvm::SmallString<128> CfgFileName(FileName);
740 llvm::sys::path::native(CfgFileName);
741 ConfigFile = CfgFileName.str();
743 CfgOptions = llvm::make_unique<InputArgList>(
744 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
750 if (CfgOptions->hasArg(options::OPT_config)) {
752 Diag(diag::err_drv_nested_config_file);
756 // Claim all arguments that come from a configuration file so that the driver
757 // does not warn on any that is unused.
758 for (Arg *A : *CfgOptions)
763 bool Driver::loadConfigFile() {
764 std::string CfgFileName;
765 bool FileSpecifiedExplicitly = false;
767 // Process options that change search path for config files.
769 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
770 SmallString<128> CfgDir;
772 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
773 if (!CfgDir.empty()) {
774 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
775 SystemConfigDir.clear();
777 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
780 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
781 SmallString<128> CfgDir;
783 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
784 if (!CfgDir.empty()) {
785 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
786 UserConfigDir.clear();
788 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
793 // First try to find config file specified in command line.
795 std::vector<std::string> ConfigFiles =
796 CLOptions->getAllArgValues(options::OPT_config);
797 if (ConfigFiles.size() > 1) {
798 Diag(diag::err_drv_duplicate_config);
802 if (!ConfigFiles.empty()) {
803 CfgFileName = ConfigFiles.front();
804 assert(!CfgFileName.empty());
806 // If argument contains directory separator, treat it as a path to
807 // configuration file.
808 if (llvm::sys::path::has_parent_path(CfgFileName)) {
809 SmallString<128> CfgFilePath;
810 if (llvm::sys::path::is_relative(CfgFileName))
811 llvm::sys::fs::current_path(CfgFilePath);
812 llvm::sys::path::append(CfgFilePath, CfgFileName);
813 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
814 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
817 return readConfigFile(CfgFilePath);
820 FileSpecifiedExplicitly = true;
824 // If config file is not specified explicitly, try to deduce configuration
825 // from executable name. For instance, an executable 'armv7l-clang' will
826 // search for config file 'armv7l-clang.cfg'.
827 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
828 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
830 if (CfgFileName.empty())
833 // Determine architecture part of the file name, if it is present.
834 StringRef CfgFileArch = CfgFileName;
835 size_t ArchPrefixLen = CfgFileArch.find('-');
836 if (ArchPrefixLen == StringRef::npos)
837 ArchPrefixLen = CfgFileArch.size();
838 llvm::Triple CfgTriple;
839 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
840 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
841 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
844 if (!StringRef(CfgFileName).endswith(".cfg"))
845 CfgFileName += ".cfg";
847 // If config file starts with architecture name and command line options
848 // redefine architecture (with options like -m32 -LE etc), try finding new
849 // config file with that architecture.
850 SmallString<128> FixedConfigFile;
851 size_t FixedArchPrefixLen = 0;
853 // Get architecture name from config file name like 'i386.cfg' or
854 // 'armv7l-clang.cfg'.
855 // Check if command line options changes effective triple.
856 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
857 CfgTriple.getTriple(), *CLOptions);
858 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
859 FixedConfigFile = EffectiveTriple.getArchName();
860 FixedArchPrefixLen = FixedConfigFile.size();
861 // Append the rest of original file name so that file name transforms
862 // like: i386-clang.cfg -> x86_64-clang.cfg.
863 if (ArchPrefixLen < CfgFileName.size())
864 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
868 // Prepare list of directories where config file is searched for.
869 SmallVector<std::string, 3> CfgFileSearchDirs;
870 CfgFileSearchDirs.push_back(UserConfigDir);
871 CfgFileSearchDirs.push_back(SystemConfigDir);
872 CfgFileSearchDirs.push_back(Dir);
874 // Try to find config file. First try file with corrected architecture.
875 llvm::SmallString<128> CfgFilePath;
876 if (!FixedConfigFile.empty()) {
877 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
878 return readConfigFile(CfgFilePath);
879 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
880 FixedConfigFile.resize(FixedArchPrefixLen);
881 FixedConfigFile.append(".cfg");
882 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
883 return readConfigFile(CfgFilePath);
886 // Then try original file name.
887 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
888 return readConfigFile(CfgFilePath);
890 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
891 if (!ClangNameParts.ModeSuffix.empty() &&
892 !ClangNameParts.TargetPrefix.empty()) {
893 CfgFileName.assign(ClangNameParts.TargetPrefix);
894 CfgFileName.append(".cfg");
895 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
896 return readConfigFile(CfgFilePath);
899 // Report error but only if config file was specified explicitly, by option
900 // --config. If it was deduced from executable name, it is not an error.
901 if (FileSpecifiedExplicitly) {
902 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
903 for (const std::string &SearchDir : CfgFileSearchDirs)
904 if (!SearchDir.empty())
905 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
912 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
913 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
915 // FIXME: Handle environment options which affect driver behavior, somewhere
916 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
918 if (Optional<std::string> CompilerPathValue =
919 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
920 StringRef CompilerPath = *CompilerPathValue;
921 while (!CompilerPath.empty()) {
922 std::pair<StringRef, StringRef> Split =
923 CompilerPath.split(llvm::sys::EnvPathSeparator);
924 PrefixDirs.push_back(Split.first);
925 CompilerPath = Split.second;
929 // We look for the driver mode option early, because the mode can affect
930 // how other options are parsed.
931 ParseDriverMode(ClangExecutable, ArgList.slice(1));
933 // FIXME: What are we going to do with -V and -b?
935 // Arguments specified in command line.
937 CLOptions = llvm::make_unique<InputArgList>(
938 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
940 // Try parsing configuration file.
942 ContainsError = loadConfigFile();
943 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
945 // All arguments, from both config file and command line.
946 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
947 : std::move(*CLOptions));
949 auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
950 unsigned Index = Args.MakeIndex(Opt->getSpelling());
951 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
953 Copy->getValues() = Opt->getValues();
954 if (Opt->isClaimed())
960 for (auto *Opt : *CLOptions) {
961 if (Opt->getOption().matches(options::OPT_config))
963 const Arg *BaseArg = &Opt->getBaseArg();
966 appendOneArg(Opt, BaseArg);
969 // In CL mode, look for any pass-through arguments
970 if (IsCLMode() && !ContainsError) {
971 SmallVector<const char *, 16> CLModePassThroughArgList;
972 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
974 CLModePassThroughArgList.push_back(A->getValue());
977 if (!CLModePassThroughArgList.empty()) {
978 // Parse any pass through args using default clang processing rather
979 // than clang-cl processing.
980 auto CLModePassThroughOptions = llvm::make_unique<InputArgList>(
981 ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
984 for (auto *Opt : *CLModePassThroughOptions) {
985 appendOneArg(Opt, nullptr);
990 // FIXME: This stuff needs to go into the Compilation, not the driver.
993 // Silence driver warnings if requested
994 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
996 // -no-canonical-prefixes is used very early in main.
997 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1000 Args.ClaimAllArgs(options::OPT_pipe);
1002 // Extract -ccc args.
1004 // FIXME: We need to figure out where this behavior should live. Most of it
1005 // should be outside in the client; the parts that aren't should have proper
1006 // options, either by introducing new ones or by overloading gcc ones like -V
1008 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1009 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1010 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1011 CCCGenericGCCName = A->getValue();
1012 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1013 options::OPT_fno_crash_diagnostics,
1014 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
1015 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1016 // and getToolChain is const.
1018 // clang-cl targets MSVC-style Win32.
1019 llvm::Triple T(TargetTriple);
1020 T.setOS(llvm::Triple::Win32);
1021 T.setVendor(llvm::Triple::PC);
1022 T.setEnvironment(llvm::Triple::MSVC);
1023 T.setObjectFormat(llvm::Triple::COFF);
1024 TargetTriple = T.str();
1026 if (const Arg *A = Args.getLastArg(options::OPT_target))
1027 TargetTriple = A->getValue();
1028 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1029 Dir = InstalledDir = A->getValue();
1030 for (const Arg *A : Args.filtered(options::OPT_B)) {
1032 PrefixDirs.push_back(A->getValue(0));
1034 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1035 SysRoot = A->getValue();
1036 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1037 DyldPrefix = A->getValue();
1039 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1040 ResourceDir = A->getValue();
1042 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1043 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1044 .Case("cwd", SaveTempsCwd)
1045 .Case("obj", SaveTempsObj)
1046 .Default(SaveTempsCwd);
1051 // Process -fembed-bitcode= flags.
1052 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1053 StringRef Name = A->getValue();
1054 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1055 .Case("off", EmbedNone)
1056 .Case("all", EmbedBitcode)
1057 .Case("bitcode", EmbedBitcode)
1058 .Case("marker", EmbedMarker)
1061 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1064 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1067 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1068 llvm::make_unique<InputArgList>(std::move(Args));
1070 // Perform the default argument translations.
1071 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1073 // Owned by the host.
1074 const ToolChain &TC = getToolChain(
1075 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1077 // The compilation takes ownership of Args.
1078 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1081 if (!HandleImmediateArgs(*C))
1084 // Construct the list of inputs.
1086 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1088 // Populate the tool chains for the offloading devices, if any.
1089 CreateOffloadingDeviceToolChains(*C, Inputs);
1091 // Construct the list of abstract actions to perform for this compilation. On
1092 // MachO targets this uses the driver-driver and universal actions.
1093 if (TC.getTriple().isOSBinFormatMachO())
1094 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1096 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1098 if (CCCPrintPhases) {
1108 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1109 llvm::opt::ArgStringList ASL;
1110 for (const auto *A : Args)
1111 A->render(Args, ASL);
1113 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1114 if (I != ASL.begin())
1116 Command::printArg(OS, *I, true);
1121 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1122 SmallString<128> &CrashDiagDir) {
1123 using namespace llvm::sys;
1124 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1125 "Only knows about .crash files on Darwin");
1127 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1128 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1129 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1130 path::home_directory(CrashDiagDir);
1131 if (CrashDiagDir.startswith("/var/root"))
1133 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1141 fs::file_status FileStatus;
1142 TimePoint<> LastAccessTime;
1143 SmallString<128> CrashFilePath;
1144 // Lookup the .crash files and get the one generated by a subprocess spawned
1145 // by this driver invocation.
1146 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1147 File != FileEnd && !EC; File.increment(EC)) {
1148 StringRef FileName = path::filename(File->path());
1149 if (!FileName.startswith(Name))
1151 if (fs::status(File->path(), FileStatus))
1153 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1154 llvm::MemoryBuffer::getFile(File->path());
1157 // The first line should start with "Process:", otherwise this isn't a real
1159 StringRef Data = CrashFile.get()->getBuffer();
1160 if (!Data.startswith("Process:"))
1162 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1163 size_t ParentProcPos = Data.find("Parent Process:");
1164 if (ParentProcPos == StringRef::npos)
1166 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1167 if (LineEnd == StringRef::npos)
1169 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1170 int OpenBracket = -1, CloseBracket = -1;
1171 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1172 if (ParentProcess[i] == '[')
1174 if (ParentProcess[i] == ']')
1177 // Extract the parent process PID from the .crash file and check whether
1178 // it matches this driver invocation pid.
1180 if (OpenBracket < 0 || CloseBracket < 0 ||
1181 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1182 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1186 // Found a .crash file matching the driver pid. To avoid getting an older
1187 // and misleading crash file, continue looking for the most recent.
1188 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1189 // multiple crashes poiting to the same parent process. Since the driver
1190 // does not collect pid information for the dispatched invocation there's
1191 // currently no way to distinguish among them.
1192 const auto FileAccessTime = FileStatus.getLastModificationTime();
1193 if (FileAccessTime > LastAccessTime) {
1194 CrashFilePath.assign(File->path());
1195 LastAccessTime = FileAccessTime;
1199 // If found, copy it over to the location of other reproducer files.
1200 if (!CrashFilePath.empty()) {
1201 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1210 // When clang crashes, produce diagnostic information including the fully
1211 // preprocessed source file(s). Request that the developer attach the
1212 // diagnostic information to a bug report.
1213 void Driver::generateCompilationDiagnostics(
1214 Compilation &C, const Command &FailingCommand,
1215 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1216 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1219 // Don't try to generate diagnostics for link or dsymutil jobs.
1220 if (FailingCommand.getCreator().isLinkJob() ||
1221 FailingCommand.getCreator().isDsymutilJob())
1224 // Print the version of the compiler.
1225 PrintVersion(C, llvm::errs());
1227 Diag(clang::diag::note_drv_command_failed_diag_msg)
1228 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1229 "crash backtrace, preprocessed source, and associated run script.";
1231 // Suppress driver output and emit preprocessor output to temp file.
1233 CCGenDiagnostics = true;
1235 // Save the original job command(s).
1236 Command Cmd = FailingCommand;
1238 // Keep track of whether we produce any errors while trying to produce
1239 // preprocessed sources.
1240 DiagnosticErrorTrap Trap(Diags);
1242 // Suppress tool output.
1243 C.initCompilationForDiagnostics();
1245 // Construct the list of inputs.
1247 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1249 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1250 bool IgnoreInput = false;
1252 // Ignore input from stdin or any inputs that cannot be preprocessed.
1253 // Check type first as not all linker inputs have a value.
1254 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1256 } else if (!strcmp(it->second->getValue(), "-")) {
1257 Diag(clang::diag::note_drv_command_failed_diag_msg)
1258 << "Error generating preprocessed source(s) - "
1259 "ignoring input from stdin.";
1264 it = Inputs.erase(it);
1271 if (Inputs.empty()) {
1272 Diag(clang::diag::note_drv_command_failed_diag_msg)
1273 << "Error generating preprocessed source(s) - "
1274 "no preprocessable inputs.";
1278 // Don't attempt to generate preprocessed files if multiple -arch options are
1279 // used, unless they're all duplicates.
1280 llvm::StringSet<> ArchNames;
1281 for (const Arg *A : C.getArgs()) {
1282 if (A->getOption().matches(options::OPT_arch)) {
1283 StringRef ArchName = A->getValue();
1284 ArchNames.insert(ArchName);
1287 if (ArchNames.size() > 1) {
1288 Diag(clang::diag::note_drv_command_failed_diag_msg)
1289 << "Error generating preprocessed source(s) - cannot generate "
1290 "preprocessed source with multiple -arch options.";
1294 // Construct the list of abstract actions to perform for this compilation. On
1295 // Darwin OSes this uses the driver-driver and builds universal actions.
1296 const ToolChain &TC = C.getDefaultToolChain();
1297 if (TC.getTriple().isOSBinFormatMachO())
1298 BuildUniversalActions(C, TC, Inputs);
1300 BuildActions(C, C.getArgs(), Inputs, C.getActions());
1304 // If there were errors building the compilation, quit now.
1305 if (Trap.hasErrorOccurred()) {
1306 Diag(clang::diag::note_drv_command_failed_diag_msg)
1307 << "Error generating preprocessed source(s).";
1311 // Generate preprocessed output.
1312 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1313 C.ExecuteJobs(C.getJobs(), FailingCommands);
1315 // If any of the preprocessing commands failed, clean up and exit.
1316 if (!FailingCommands.empty()) {
1317 Diag(clang::diag::note_drv_command_failed_diag_msg)
1318 << "Error generating preprocessed source(s).";
1322 const ArgStringList &TempFiles = C.getTempFiles();
1323 if (TempFiles.empty()) {
1324 Diag(clang::diag::note_drv_command_failed_diag_msg)
1325 << "Error generating preprocessed source(s).";
1329 Diag(clang::diag::note_drv_command_failed_diag_msg)
1330 << "\n********************\n\n"
1331 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1332 "Preprocessed source(s) and associated run script(s) are located at:";
1334 SmallString<128> VFS;
1335 SmallString<128> ReproCrashFilename;
1336 for (const char *TempFile : TempFiles) {
1337 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1339 Report->TemporaryFiles.push_back(TempFile);
1340 if (ReproCrashFilename.empty()) {
1341 ReproCrashFilename = TempFile;
1342 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1344 if (StringRef(TempFile).endswith(".cache")) {
1345 // In some cases (modules) we'll dump extra data to help with reproducing
1346 // the crash into a directory next to the output.
1347 VFS = llvm::sys::path::filename(TempFile);
1348 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1352 // Assume associated files are based off of the first temporary file.
1353 CrashReportInfo CrashInfo(TempFiles[0], VFS);
1355 llvm::SmallString<128> Script(CrashInfo.Filename);
1356 llvm::sys::path::replace_extension(Script, "sh");
1358 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
1360 Diag(clang::diag::note_drv_command_failed_diag_msg)
1361 << "Error generating run script: " << Script << " " << EC.message();
1363 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1364 << "# Driver args: ";
1365 printArgList(ScriptOS, C.getInputArgs());
1366 ScriptOS << "# Original command: ";
1367 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1368 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1369 if (!AdditionalInformation.empty())
1370 ScriptOS << "\n# Additional information: " << AdditionalInformation
1373 Report->TemporaryFiles.push_back(Script.str());
1374 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1377 // On darwin, provide information about the .crash diagnostic report.
1378 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1379 SmallString<128> CrashDiagDir;
1380 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1381 Diag(clang::diag::note_drv_command_failed_diag_msg)
1382 << ReproCrashFilename.str();
1383 } else { // Suggest a directory for the user to look for .crash files.
1384 llvm::sys::path::append(CrashDiagDir, Name);
1385 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1386 Diag(clang::diag::note_drv_command_failed_diag_msg)
1387 << "Crash backtrace is located in";
1388 Diag(clang::diag::note_drv_command_failed_diag_msg)
1389 << CrashDiagDir.str();
1390 Diag(clang::diag::note_drv_command_failed_diag_msg)
1391 << "(choose the .crash file that corresponds to your crash)";
1395 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1396 options::OPT_frewrite_map_file_EQ))
1397 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1399 Diag(clang::diag::note_drv_command_failed_diag_msg)
1400 << "\n\n********************";
1403 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1404 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
1405 // if the tool does not support response files, there is a chance/ that things
1406 // will just work without a response file, so we silently just skip it.
1407 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1408 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
1411 std::string TmpName = GetTemporaryPath("response", "txt");
1412 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1415 int Driver::ExecuteCompilation(
1417 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1418 // Just print if -### was present.
1419 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1420 C.getJobs().Print(llvm::errs(), "\n", true);
1424 // If there were errors building the compilation, quit now.
1425 if (Diags.hasErrorOccurred())
1428 // Set up response file names for each command, if necessary
1429 for (auto &Job : C.getJobs())
1430 setUpResponseFiles(C, Job);
1432 C.ExecuteJobs(C.getJobs(), FailingCommands);
1434 // If the command succeeded, we are done.
1435 if (FailingCommands.empty())
1438 // Otherwise, remove result files and print extra information about abnormal
1441 for (const auto &CmdPair : FailingCommands) {
1442 int CommandRes = CmdPair.first;
1443 const Command *FailingCommand = CmdPair.second;
1445 // Remove result files if we're not saving temps.
1446 if (!isSaveTempsEnabled()) {
1447 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1448 C.CleanupFileMap(C.getResultFiles(), JA, true);
1450 // Failure result files are valid unless we crashed.
1452 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1456 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1457 // for SIGPIPE. Do not print diagnostics for this case.
1458 if (CommandRes == EX_IOERR) {
1464 // Print extra information about abnormal failures, if possible.
1466 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1467 // status was 1, assume the command failed normally. In particular, if it
1468 // was the compiler then assume it gave a reasonable error code. Failures
1469 // in other tools are less common, and they generally have worse
1470 // diagnostics, so always print the diagnostic there.
1471 const Tool &FailingTool = FailingCommand->getCreator();
1473 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1474 // FIXME: See FIXME above regarding result code interpretation.
1476 Diag(clang::diag::err_drv_command_signalled)
1477 << FailingTool.getShortName();
1479 Diag(clang::diag::err_drv_command_failed)
1480 << FailingTool.getShortName() << CommandRes;
1486 void Driver::PrintHelp(bool ShowHidden) const {
1487 unsigned IncludedFlagsBitmask;
1488 unsigned ExcludedFlagsBitmask;
1489 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1490 getIncludeExcludeOptionFlagMasks(IsCLMode());
1492 ExcludedFlagsBitmask |= options::NoDriverOption;
1494 ExcludedFlagsBitmask |= HelpHidden;
1496 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1497 getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1498 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1499 /*ShowAllAliases=*/false);
1502 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1503 // FIXME: The following handlers should use a callback mechanism, we don't
1504 // know what the client would like to do.
1505 OS << getClangFullVersion() << '\n';
1506 const ToolChain &TC = C.getDefaultToolChain();
1507 OS << "Target: " << TC.getTripleString() << '\n';
1509 // Print the threading model.
1510 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1511 // Don't print if the ToolChain would have barfed on it already
1512 if (TC.isThreadModelSupported(A->getValue()))
1513 OS << "Thread model: " << A->getValue();
1515 OS << "Thread model: " << TC.getThreadModel();
1518 // Print out the install directory.
1519 OS << "InstalledDir: " << InstalledDir << '\n';
1521 // If configuration file was used, print its path.
1522 if (!ConfigFile.empty())
1523 OS << "Configuration file: " << ConfigFile << '\n';
1526 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1528 static void PrintDiagnosticCategories(raw_ostream &OS) {
1529 // Skip the empty category.
1530 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1532 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1535 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1536 if (PassedFlags == "")
1538 // Print out all options that start with a given argument. This is used for
1539 // shell autocompletion.
1540 std::vector<std::string> SuggestedCompletions;
1541 std::vector<std::string> Flags;
1543 unsigned short DisableFlags =
1544 options::NoDriverOption | options::Unsupported | options::Ignored;
1546 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1547 // because the latter indicates that the user put space before pushing tab
1548 // which should end up in a file completion.
1549 const bool HasSpace = PassedFlags.endswith(",");
1551 // Parse PassedFlags by "," as all the command-line flags are passed to this
1552 // function separated by ","
1553 StringRef TargetFlags = PassedFlags;
1554 while (TargetFlags != "") {
1556 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1557 Flags.push_back(std::string(CurFlag));
1560 // We want to show cc1-only options only when clang is invoked with -cc1 or
1562 if (std::find(Flags.begin(), Flags.end(), "-Xclang") != Flags.end() ||
1563 std::find(Flags.begin(), Flags.end(), "-cc1") != Flags.end())
1564 DisableFlags &= ~options::NoDriverOption;
1567 Cur = Flags.at(Flags.size() - 1);
1569 if (Flags.size() >= 2) {
1570 Prev = Flags.at(Flags.size() - 2);
1571 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1574 if (SuggestedCompletions.empty())
1575 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1577 // If Flags were empty, it means the user typed `clang [tab]` where we should
1578 // list all possible flags. If there was no value completion and the user
1579 // pressed tab after a space, we should fall back to a file completion.
1580 // We're printing a newline to be consistent with what we print at the end of
1582 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1583 llvm::outs() << '\n';
1587 // When flag ends with '=' and there was no value completion, return empty
1588 // string and fall back to the file autocompletion.
1589 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1590 // If the flag is in the form of "--autocomplete=-foo",
1591 // we were requested to print out all option names that start with "-foo".
1592 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1593 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
1595 // We have to query the -W flags manually as they're not in the OptTable.
1596 // TODO: Find a good way to add them to OptTable instead and them remove
1598 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1599 if (S.startswith(Cur))
1600 SuggestedCompletions.push_back(S);
1603 // Sort the autocomplete candidates so that shells print them out in a
1604 // deterministic order. We could sort in any way, but we chose
1605 // case-insensitive sorting for consistency with the -help option
1606 // which prints out options in the case-insensitive alphabetical order.
1607 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1608 if (int X = A.compare_lower(B))
1610 return A.compare(B) > 0;
1613 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1616 bool Driver::HandleImmediateArgs(const Compilation &C) {
1617 // The order these options are handled in gcc is all over the place, but we
1618 // don't expect inconsistencies w.r.t. that to matter in practice.
1620 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1621 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1625 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1626 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1627 // return an answer which matches our definition of __VERSION__.
1629 // If we want to return a more correct answer some day, then we should
1630 // introduce a non-pedantically GCC compatible mode to Clang in which we
1631 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1632 llvm::outs() << "4.2.1\n";
1636 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1637 PrintDiagnosticCategories(llvm::outs());
1641 if (C.getArgs().hasArg(options::OPT_help) ||
1642 C.getArgs().hasArg(options::OPT__help_hidden)) {
1643 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1647 if (C.getArgs().hasArg(options::OPT__version)) {
1648 // Follow gcc behavior and use stdout for --version and stderr for -v.
1649 PrintVersion(C, llvm::outs());
1653 if (C.getArgs().hasArg(options::OPT_v) ||
1654 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1655 PrintVersion(C, llvm::errs());
1656 SuppressMissingInputWarning = true;
1659 if (C.getArgs().hasArg(options::OPT_v)) {
1660 if (!SystemConfigDir.empty())
1661 llvm::errs() << "System configuration file directory: "
1662 << SystemConfigDir << "\n";
1663 if (!UserConfigDir.empty())
1664 llvm::errs() << "User configuration file directory: "
1665 << UserConfigDir << "\n";
1668 const ToolChain &TC = C.getDefaultToolChain();
1670 if (C.getArgs().hasArg(options::OPT_v))
1671 TC.printVerboseInfo(llvm::errs());
1673 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1674 llvm::outs() << ResourceDir << '\n';
1678 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1679 llvm::outs() << "programs: =";
1680 bool separator = false;
1681 for (const std::string &Path : TC.getProgramPaths()) {
1683 llvm::outs() << ':';
1684 llvm::outs() << Path;
1687 llvm::outs() << "\n";
1688 llvm::outs() << "libraries: =" << ResourceDir;
1690 StringRef sysroot = C.getSysRoot();
1692 for (const std::string &Path : TC.getFilePaths()) {
1693 // Always print a separator. ResourceDir was the first item shown.
1694 llvm::outs() << ':';
1695 // Interpretation of leading '=' is needed only for NetBSD.
1697 llvm::outs() << sysroot << Path.substr(1);
1699 llvm::outs() << Path;
1701 llvm::outs() << "\n";
1705 // FIXME: The following handlers should use a callback mechanism, we don't
1706 // know what the client would like to do.
1707 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1708 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1712 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1713 StringRef ProgName = A->getValue();
1715 // Null program name cannot have a path.
1716 if (! ProgName.empty())
1717 llvm::outs() << GetProgramPath(ProgName, TC);
1719 llvm::outs() << "\n";
1723 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1724 StringRef PassedFlags = A->getValue();
1725 HandleAutocompletions(PassedFlags);
1729 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1730 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1731 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1732 RegisterEffectiveTriple TripleRAII(TC, Triple);
1734 case ToolChain::RLT_CompilerRT:
1735 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1737 case ToolChain::RLT_Libgcc:
1738 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1744 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1745 for (const Multilib &Multilib : TC.getMultilibs())
1746 llvm::outs() << Multilib << "\n";
1750 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1751 const Multilib &Multilib = TC.getMultilib();
1752 if (Multilib.gccSuffix().empty())
1753 llvm::outs() << ".\n";
1755 StringRef Suffix(Multilib.gccSuffix());
1756 assert(Suffix.front() == '/');
1757 llvm::outs() << Suffix.substr(1) << "\n";
1762 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1763 llvm::outs() << TC.getTripleString() << "\n";
1767 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1768 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1769 llvm::outs() << Triple.getTriple() << "\n";
1776 // Display an action graph human-readably. Action A is the "sink" node
1777 // and latest-occuring action. Traversal is in pre-order, visiting the
1778 // inputs to each action before printing the action itself.
1779 static unsigned PrintActions1(const Compilation &C, Action *A,
1780 std::map<Action *, unsigned> &Ids) {
1781 if (Ids.count(A)) // A was already visited.
1785 llvm::raw_string_ostream os(str);
1787 os << Action::getClassName(A->getKind()) << ", ";
1788 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1789 os << "\"" << IA->getInputArg().getValue() << "\"";
1790 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1791 os << '"' << BIA->getArchName() << '"' << ", {"
1792 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1793 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1794 bool IsFirst = true;
1795 OA->doOnEachDependence(
1796 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1797 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1798 // sm_35 this will generate:
1799 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1800 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1805 os << A->getOffloadingKindPrefix();
1809 os << TC->getTriple().normalize();
1812 os << ":" << BoundArch;
1815 os << " {" << PrintActions1(C, A, Ids) << "}";
1819 const ActionList *AL = &A->getInputs();
1822 const char *Prefix = "{";
1823 for (Action *PreRequisite : *AL) {
1824 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1832 // Append offload info for all options other than the offloading action
1833 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1834 std::string offload_str;
1835 llvm::raw_string_ostream offload_os(offload_str);
1836 if (!isa<OffloadAction>(A)) {
1837 auto S = A->getOffloadingKindPrefix();
1839 offload_os << ", (" << S;
1840 if (A->getOffloadingArch())
1841 offload_os << ", " << A->getOffloadingArch();
1846 unsigned Id = Ids.size();
1848 llvm::errs() << Id << ": " << os.str() << ", "
1849 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1854 // Print the action graphs in a compilation C.
1855 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1856 void Driver::PrintActions(const Compilation &C) const {
1857 std::map<Action *, unsigned> Ids;
1858 for (Action *A : C.getActions())
1859 PrintActions1(C, A, Ids);
1862 /// Check whether the given input tree contains any compilation or
1863 /// assembly actions.
1864 static bool ContainsCompileOrAssembleAction(const Action *A) {
1865 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1866 isa<AssembleJobAction>(A))
1869 for (const Action *Input : A->inputs())
1870 if (ContainsCompileOrAssembleAction(Input))
1876 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1877 const InputList &BAInputs) const {
1878 DerivedArgList &Args = C.getArgs();
1879 ActionList &Actions = C.getActions();
1880 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1881 // Collect the list of architectures. Duplicates are allowed, but should only
1882 // be handled once (in the order seen).
1883 llvm::StringSet<> ArchNames;
1884 SmallVector<const char *, 4> Archs;
1885 for (Arg *A : Args) {
1886 if (A->getOption().matches(options::OPT_arch)) {
1887 // Validate the option here; we don't save the type here because its
1888 // particular spelling may participate in other driver choices.
1889 llvm::Triple::ArchType Arch =
1890 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1891 if (Arch == llvm::Triple::UnknownArch) {
1892 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1897 if (ArchNames.insert(A->getValue()).second)
1898 Archs.push_back(A->getValue());
1902 // When there is no explicit arch for this platform, make sure we still bind
1903 // the architecture (to the default) so that -Xarch_ is handled correctly.
1905 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1907 ActionList SingleActions;
1908 BuildActions(C, Args, BAInputs, SingleActions);
1910 // Add in arch bindings for every top level action, as well as lipo and
1911 // dsymutil steps if needed.
1912 for (Action* Act : SingleActions) {
1913 // Make sure we can lipo this kind of output. If not (and it is an actual
1914 // output) then we disallow, since we can't create an output file with the
1915 // right name without overwriting it. We could remove this oddity by just
1916 // changing the output names to include the arch, which would also fix
1917 // -save-temps. Compatibility wins for now.
1919 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1920 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1921 << types::getTypeName(Act->getType());
1924 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1925 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1927 // Lipo if necessary, we do it this way because we need to set the arch flag
1928 // so that -Xarch_ gets overwritten.
1929 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1930 Actions.append(Inputs.begin(), Inputs.end());
1932 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1934 // Handle debug info queries.
1935 Arg *A = Args.getLastArg(options::OPT_g_Group);
1936 if (A && !A->getOption().matches(options::OPT_g0) &&
1937 !A->getOption().matches(options::OPT_gstabs) &&
1938 ContainsCompileOrAssembleAction(Actions.back())) {
1940 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1941 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1942 // because the debug info will refer to a temporary object file which
1943 // will be removed at the end of the compilation process.
1944 if (Act->getType() == types::TY_Image) {
1946 Inputs.push_back(Actions.back());
1949 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1952 // Verify the debug info output.
1953 if (Args.hasArg(options::OPT_verify_debug_info)) {
1954 Action* LastAction = Actions.back();
1956 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1957 LastAction, types::TY_Nothing));
1963 /// Check that the file referenced by Value exists. If it doesn't,
1964 /// issue a diagnostic and return false.
1965 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1966 StringRef Value, types::ID Ty) {
1967 if (!D.getCheckInputsExist())
1970 // stdin always exists.
1974 SmallString<64> Path(Value);
1975 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1976 if (!llvm::sys::path::is_absolute(Path)) {
1977 SmallString<64> Directory(WorkDir->getValue());
1978 llvm::sys::path::append(Directory, Value);
1979 Path.assign(Directory);
1983 if (D.getVFS().exists(Path))
1987 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1988 llvm::sys::Process::FindInEnvPath("LIB", Value))
1991 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1992 // Arguments to the /link flag might cause the linker to search for object
1993 // and library files in paths we don't know about. Don't error in such
1999 D.Diag(clang::diag::err_drv_no_such_file) << Path;
2003 // Construct a the list of inputs and their types.
2004 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2005 InputList &Inputs) const {
2006 // Track the current user specified (-x) input. We also explicitly track the
2007 // argument used to set the type; we only want to claim the type when we
2008 // actually use it, so we warn about unused -x arguments.
2009 types::ID InputType = types::TY_Nothing;
2010 Arg *InputTypeArg = nullptr;
2012 // The last /TC or /TP option sets the input type to C or C++ globally.
2013 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2014 options::OPT__SLASH_TP)) {
2015 InputTypeArg = TCTP;
2016 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2020 Arg *Previous = nullptr;
2021 bool ShowNote = false;
2022 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2024 Diag(clang::diag::warn_drv_overriding_flag_option)
2025 << Previous->getSpelling() << A->getSpelling();
2031 Diag(clang::diag::note_drv_t_option_is_global);
2033 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2034 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2037 for (Arg *A : Args) {
2038 if (A->getOption().getKind() == Option::InputClass) {
2039 const char *Value = A->getValue();
2040 types::ID Ty = types::TY_INVALID;
2042 // Infer the input type if necessary.
2043 if (InputType == types::TY_Nothing) {
2044 // If there was an explicit arg for this, claim it.
2046 InputTypeArg->claim();
2048 // stdin must be handled specially.
2049 if (memcmp(Value, "-", 2) == 0) {
2050 // If running with -E, treat as a C input (this changes the builtin
2051 // macros, for example). This may be overridden by -ObjC below.
2053 // Otherwise emit an error but still use a valid type to avoid
2054 // spurious errors (e.g., no inputs).
2055 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2056 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2057 : clang::diag::err_drv_unknown_stdin_type);
2060 // Otherwise lookup by extension.
2061 // Fallback is C if invoked as C preprocessor, C++ if invoked with
2062 // clang-cl /E, or Object otherwise.
2063 // We use a host hook here because Darwin at least has its own
2064 // idea of what .s is.
2065 if (const char *Ext = strrchr(Value, '.'))
2066 Ty = TC.LookupTypeForExtension(Ext + 1);
2068 if (Ty == types::TY_INVALID) {
2071 else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2074 Ty = types::TY_Object;
2077 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2078 // should autodetect some input files as C++ for g++ compatibility.
2080 types::ID OldTy = Ty;
2081 Ty = types::lookupCXXTypeForCType(Ty);
2084 Diag(clang::diag::warn_drv_treating_input_as_cxx)
2085 << getTypeName(OldTy) << getTypeName(Ty);
2089 // -ObjC and -ObjC++ override the default language, but only for "source
2090 // files". We just treat everything that isn't a linker input as a
2093 // FIXME: Clean this up if we move the phase sequence into the type.
2094 if (Ty != types::TY_Object) {
2095 if (Args.hasArg(options::OPT_ObjC))
2096 Ty = types::TY_ObjC;
2097 else if (Args.hasArg(options::OPT_ObjCXX))
2098 Ty = types::TY_ObjCXX;
2101 assert(InputTypeArg && "InputType set w/o InputTypeArg");
2102 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2103 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2105 const char *Ext = strrchr(Value, '.');
2106 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2107 Ty = types::TY_Object;
2109 if (Ty == types::TY_INVALID) {
2111 InputTypeArg->claim();
2115 if (DiagnoseInputExistence(*this, Args, Value, Ty))
2116 Inputs.push_back(std::make_pair(Ty, A));
2118 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2119 StringRef Value = A->getValue();
2120 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
2121 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
2122 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2125 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2126 StringRef Value = A->getValue();
2127 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
2128 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
2129 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2132 } else if (A->getOption().hasFlag(options::LinkerInput)) {
2133 // Just treat as object type, we could make a special type for this if
2135 Inputs.push_back(std::make_pair(types::TY_Object, A));
2137 } else if (A->getOption().matches(options::OPT_x)) {
2139 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2142 // Follow gcc behavior and treat as linker input for invalid -x
2143 // options. Its not clear why we shouldn't just revert to unknown; but
2144 // this isn't very important, we might as well be bug compatible.
2146 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2147 InputType = types::TY_Object;
2149 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2150 assert(A->getNumValues() == 1 && "The /U option has one value.");
2151 StringRef Val = A->getValue(0);
2152 if (Val.find_first_of("/\\") != StringRef::npos) {
2153 // Warn about e.g. "/Users/me/myfile.c".
2154 Diag(diag::warn_slash_u_filename) << Val;
2155 Diag(diag::note_use_dashdash);
2159 if (CCCIsCPP() && Inputs.empty()) {
2160 // If called as standalone preprocessor, stdin is processed
2161 // if no other input is present.
2162 Arg *A = MakeInputArg(Args, *Opts, "-");
2163 Inputs.push_back(std::make_pair(types::TY_C, A));
2168 /// Provides a convenient interface for different programming models to generate
2169 /// the required device actions.
2170 class OffloadingActionBuilder final {
2171 /// Flag used to trace errors in the builder.
2172 bool IsValid = false;
2174 /// The compilation that is using this builder.
2177 /// Map between an input argument and the offload kinds used to process it.
2178 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2180 /// Builder interface. It doesn't build anything or keep any state.
2181 class DeviceActionBuilder {
2183 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2185 enum ActionBuilderReturnCode {
2186 // The builder acted successfully on the current action.
2188 // The builder didn't have to act on the current action.
2190 // The builder was successful and requested the host action to not be
2196 /// Compilation associated with this builder.
2199 /// Tool chains associated with this builder. The same programming
2200 /// model may have associated one or more tool chains.
2201 SmallVector<const ToolChain *, 2> ToolChains;
2203 /// The derived arguments associated with this builder.
2204 DerivedArgList &Args;
2206 /// The inputs associated with this builder.
2207 const Driver::InputList &Inputs;
2209 /// The associated offload kind.
2210 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2213 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2214 const Driver::InputList &Inputs,
2215 Action::OffloadKind AssociatedOffloadKind)
2216 : C(C), Args(Args), Inputs(Inputs),
2217 AssociatedOffloadKind(AssociatedOffloadKind) {}
2218 virtual ~DeviceActionBuilder() {}
2220 /// Fill up the array \a DA with all the device dependences that should be
2221 /// added to the provided host action \a HostAction. By default it is
2223 virtual ActionBuilderReturnCode
2224 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2225 phases::ID CurPhase, phases::ID FinalPhase,
2227 return ABRT_Inactive;
2230 /// Update the state to include the provided host action \a HostAction as a
2231 /// dependency of the current device action. By default it is inactive.
2232 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2233 return ABRT_Inactive;
2236 /// Append top level actions generated by the builder. Return true if errors
2238 virtual void appendTopLevelActions(ActionList &AL) {}
2240 /// Append linker actions generated by the builder. Return true if errors
2242 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2244 /// Initialize the builder. Return true if any initialization errors are
2246 virtual bool initialize() { return false; }
2248 /// Return true if the builder can use bundling/unbundling.
2249 virtual bool canUseBundlerUnbundler() const { return false; }
2251 /// Return true if this builder is valid. We have a valid builder if we have
2252 /// associated device tool chains.
2253 bool isValid() { return !ToolChains.empty(); }
2255 /// Return the associated offload kind.
2256 Action::OffloadKind getAssociatedOffloadKind() {
2257 return AssociatedOffloadKind;
2261 /// Base class for CUDA/HIP action builder. It injects device code in
2262 /// the host backend action.
2263 class CudaActionBuilderBase : public DeviceActionBuilder {
2265 /// Flags to signal if the user requested host-only or device-only
2267 bool CompileHostOnly = false;
2268 bool CompileDeviceOnly = false;
2270 /// List of GPU architectures to use in this compilation.
2271 SmallVector<CudaArch, 4> GpuArchList;
2273 /// The CUDA actions for the current input.
2274 ActionList CudaDeviceActions;
2276 /// The CUDA fat binary if it was generated for the current input.
2277 Action *CudaFatBinary = nullptr;
2279 /// Flag that is set to true if this builder acted on the current input.
2280 bool IsActive = false;
2282 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2283 const Driver::InputList &Inputs,
2284 Action::OffloadKind OFKind)
2285 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2287 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2288 // While generating code for CUDA, we only depend on the host input action
2289 // to trigger the creation of all the CUDA device actions.
2291 // If we are dealing with an input action, replicate it for each GPU
2292 // architecture. If we are in host-only mode we return 'success' so that
2293 // the host uses the CUDA offload kind.
2294 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2295 assert(!GpuArchList.empty() &&
2296 "We should have at least one GPU architecture.");
2298 // If the host input is not CUDA or HIP, we don't need to bother about
2300 if (IA->getType() != types::TY_CUDA &&
2301 IA->getType() != types::TY_HIP) {
2302 // The builder will ignore this input.
2304 return ABRT_Inactive;
2307 // Set the flag to true, so that the builder acts on the current input.
2310 if (CompileHostOnly)
2311 return ABRT_Success;
2313 // Replicate inputs for each GPU architecture.
2314 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2315 : types::TY_CUDA_DEVICE;
2316 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2317 CudaDeviceActions.push_back(
2318 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2321 return ABRT_Success;
2324 // If this is an unbundling action use it as is for each CUDA toolchain.
2325 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2326 CudaDeviceActions.clear();
2327 auto *IA = cast<InputAction>(UA->getInputs().back());
2328 std::string FileName = IA->getInputArg().getAsString(Args);
2329 // Check if the type of the file is the same as the action. Do not
2330 // unbundle it if it is not. Do not unbundle .so files, for example,
2331 // which are not object files.
2332 if (IA->getType() == types::TY_Object &&
2333 (!llvm::sys::path::has_extension(FileName) ||
2334 types::lookupTypeForExtension(
2335 llvm::sys::path::extension(FileName).drop_front()) !=
2337 return ABRT_Inactive;
2339 for (auto Arch : GpuArchList) {
2340 CudaDeviceActions.push_back(UA);
2341 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2342 AssociatedOffloadKind);
2344 return ABRT_Success;
2347 return IsActive ? ABRT_Success : ABRT_Inactive;
2350 void appendTopLevelActions(ActionList &AL) override {
2351 // Utility to append actions to the top level list.
2352 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2353 OffloadAction::DeviceDependences Dep;
2354 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2355 AssociatedOffloadKind);
2356 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2359 // If we have a fat binary, add it to the list.
2360 if (CudaFatBinary) {
2361 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2362 CudaDeviceActions.clear();
2363 CudaFatBinary = nullptr;
2367 if (CudaDeviceActions.empty())
2370 // If we have CUDA actions at this point, that's because we have a have
2371 // partial compilation, so we should have an action for each GPU
2373 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2374 "Expecting one action per GPU architecture.");
2375 assert(ToolChains.size() == 1 &&
2376 "Expecting to have a sing CUDA toolchain.");
2377 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2378 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2380 CudaDeviceActions.clear();
2383 bool initialize() override {
2384 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2385 AssociatedOffloadKind == Action::OFK_HIP);
2387 // We don't need to support CUDA.
2388 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2389 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2392 // We don't need to support HIP.
2393 if (AssociatedOffloadKind == Action::OFK_HIP &&
2394 !C.hasOffloadToolChain<Action::OFK_HIP>())
2397 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2398 assert(HostTC && "No toolchain for host compilation.");
2399 if (HostTC->getTriple().isNVPTX() ||
2400 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2401 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2402 // an error and abort pipeline construction early so we don't trip
2403 // asserts that assume device-side compilation.
2404 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2405 << HostTC->getTriple().getArchName();
2409 ToolChains.push_back(
2410 AssociatedOffloadKind == Action::OFK_Cuda
2411 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2412 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2414 Arg *PartialCompilationArg = Args.getLastArg(
2415 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2416 options::OPT_cuda_compile_host_device);
2417 CompileHostOnly = PartialCompilationArg &&
2418 PartialCompilationArg->getOption().matches(
2419 options::OPT_cuda_host_only);
2420 CompileDeviceOnly = PartialCompilationArg &&
2421 PartialCompilationArg->getOption().matches(
2422 options::OPT_cuda_device_only);
2424 // Collect all cuda_gpu_arch parameters, removing duplicates.
2425 std::set<CudaArch> GpuArchs;
2427 for (Arg *A : Args) {
2428 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2429 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2433 const StringRef ArchStr = A->getValue();
2434 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2439 CudaArch Arch = StringToCudaArch(ArchStr);
2440 if (Arch == CudaArch::UNKNOWN) {
2441 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2443 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2444 GpuArchs.insert(Arch);
2445 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2446 GpuArchs.erase(Arch);
2448 llvm_unreachable("Unexpected option.");
2451 // Collect list of GPUs remaining in the set.
2452 for (CudaArch Arch : GpuArchs)
2453 GpuArchList.push_back(Arch);
2455 // Default to sm_20 which is the lowest common denominator for
2456 // supported GPUs. sm_20 code should work correctly, if
2457 // suboptimally, on all newer GPUs.
2458 if (GpuArchList.empty())
2459 GpuArchList.push_back(CudaArch::SM_20);
2465 /// \brief CUDA action builder. It injects device code in the host backend
2467 class CudaActionBuilder final : public CudaActionBuilderBase {
2469 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2470 const Driver::InputList &Inputs)
2471 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
2473 ActionBuilderReturnCode
2474 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2475 phases::ID CurPhase, phases::ID FinalPhase,
2476 PhasesTy &Phases) override {
2478 return ABRT_Inactive;
2480 // If we don't have more CUDA actions, we don't have any dependences to
2481 // create for the host.
2482 if (CudaDeviceActions.empty())
2483 return ABRT_Success;
2485 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2486 "Expecting one action per GPU architecture.");
2487 assert(!CompileHostOnly &&
2488 "Not expecting CUDA actions in host-only compilation.");
2490 // If we are generating code for the device or we are in a backend phase,
2491 // we attempt to generate the fat binary. We compile each arch to ptx and
2492 // assemble to cubin, then feed the cubin *and* the ptx into a device
2493 // "link" action, which uses fatbinary to combine these cubins into one
2494 // fatbin. The fatbin is then an input to the host action if not in
2495 // device-only mode.
2496 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2497 ActionList DeviceActions;
2498 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2499 // Produce the device action from the current phase up to the assemble
2501 for (auto Ph : Phases) {
2502 // Skip the phases that were already dealt with.
2505 // We have to be consistent with the host final phase.
2506 if (Ph > FinalPhase)
2509 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2510 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
2512 if (Ph == phases::Assemble)
2516 // If we didn't reach the assemble phase, we can't generate the fat
2517 // binary. We don't need to generate the fat binary if we are not in
2518 // device-only mode.
2519 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2523 Action *AssembleAction = CudaDeviceActions[I];
2524 assert(AssembleAction->getType() == types::TY_Object);
2525 assert(AssembleAction->getInputs().size() == 1);
2527 Action *BackendAction = AssembleAction->getInputs()[0];
2528 assert(BackendAction->getType() == types::TY_PP_Asm);
2530 for (auto &A : {AssembleAction, BackendAction}) {
2531 OffloadAction::DeviceDependences DDep;
2532 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2534 DeviceActions.push_back(
2535 C.MakeAction<OffloadAction>(DDep, A->getType()));
2539 // We generate the fat binary if we have device input actions.
2540 if (!DeviceActions.empty()) {
2542 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2544 if (!CompileDeviceOnly) {
2545 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2547 // Clear the fat binary, it is already a dependence to an host
2549 CudaFatBinary = nullptr;
2552 // Remove the CUDA actions as they are already connected to an host
2553 // action or fat binary.
2554 CudaDeviceActions.clear();
2557 // We avoid creating host action in device-only mode.
2558 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2559 } else if (CurPhase > phases::Backend) {
2560 // If we are past the backend phase and still have a device action, we
2561 // don't have to do anything as this action is already a device
2562 // top-level action.
2563 return ABRT_Success;
2566 assert(CurPhase < phases::Backend && "Generating single CUDA "
2567 "instructions should only occur "
2568 "before the backend phase!");
2570 // By default, we produce an action for each device arch.
2571 for (Action *&A : CudaDeviceActions)
2572 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2574 return ABRT_Success;
2577 /// \brief HIP action builder. It injects device code in the host backend
2579 class HIPActionBuilder final : public CudaActionBuilderBase {
2580 /// The linker inputs obtained for each device arch.
2581 SmallVector<ActionList, 8> DeviceLinkerInputs;
2585 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2586 const Driver::InputList &Inputs)
2587 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP),
2588 Relocatable(false) {}
2590 bool canUseBundlerUnbundler() const override { return true; }
2592 ActionBuilderReturnCode
2593 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2594 phases::ID CurPhase, phases::ID FinalPhase,
2595 PhasesTy &Phases) override {
2596 // amdgcn does not support linking of object files, therefore we skip
2597 // backend and assemble phases to output LLVM IR. Except for generating
2598 // non-relocatable device coee, where we generate fat binary for device
2599 // code and pass to host in Backend phase.
2600 if (CudaDeviceActions.empty() ||
2601 (CurPhase == phases::Backend && Relocatable) ||
2602 CurPhase == phases::Assemble)
2603 return ABRT_Success;
2605 assert(((CurPhase == phases::Link && Relocatable) ||
2606 CudaDeviceActions.size() == GpuArchList.size()) &&
2607 "Expecting one action per GPU architecture.");
2608 assert(!CompileHostOnly &&
2609 "Not expecting CUDA actions in host-only compilation.");
2611 if (!Relocatable && CurPhase == phases::Backend) {
2612 // If we are in backend phase, we attempt to generate the fat binary.
2613 // We compile each arch to IR and use a link action to generate code
2614 // object containing ISA. Then we use a special "link" action to create
2615 // a fat binary containing all the code objects for different GPU's.
2616 // The fat binary is then an input to the host action.
2617 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2618 // Create a link action to link device IR with device library
2619 // and generate ISA.
2621 AL.push_back(CudaDeviceActions[I]);
2622 CudaDeviceActions[I] =
2623 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2625 // OffloadingActionBuilder propagates device arch until an offload
2626 // action. Since the next action for creating fatbin does
2627 // not have device arch, whereas the above link action and its input
2628 // have device arch, an offload action is needed to stop the null
2629 // device arch of the next action being propagated to the above link
2631 OffloadAction::DeviceDependences DDep;
2632 DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2633 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2634 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2635 DDep, CudaDeviceActions[I]->getType());
2637 // Create HIP fat binary with a special "link" action.
2639 C.MakeAction<LinkJobAction>(CudaDeviceActions,
2640 types::TY_HIP_FATBIN);
2642 if (!CompileDeviceOnly) {
2643 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2644 AssociatedOffloadKind);
2645 // Clear the fat binary, it is already a dependence to an host
2647 CudaFatBinary = nullptr;
2650 // Remove the CUDA actions as they are already connected to an host
2651 // action or fat binary.
2652 CudaDeviceActions.clear();
2654 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2655 } else if (CurPhase == phases::Link) {
2656 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2657 // This happens to each device action originated from each input file.
2658 // Later on, device actions in DeviceLinkerInputs are used to create
2659 // device link actions in appendLinkDependences and the created device
2660 // link actions are passed to the offload action as device dependence.
2661 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2662 auto LI = DeviceLinkerInputs.begin();
2663 for (auto *A : CudaDeviceActions) {
2668 // We will pass the device action as a host dependence, so we don't
2669 // need to do anything else with them.
2670 CudaDeviceActions.clear();
2671 return ABRT_Success;
2674 // By default, we produce an action for each device arch.
2675 for (Action *&A : CudaDeviceActions)
2676 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2677 AssociatedOffloadKind);
2679 return ABRT_Success;
2682 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2683 // Append a new link action for each device.
2685 for (auto &LI : DeviceLinkerInputs) {
2686 auto *DeviceLinkAction =
2687 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2688 DA.add(*DeviceLinkAction, *ToolChains[0],
2689 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2694 bool initialize() override {
2695 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2696 options::OPT_fno_gpu_rdc, /*Default=*/false);
2698 return CudaActionBuilderBase::initialize();
2702 /// OpenMP action builder. The host bitcode is passed to the device frontend
2703 /// and all the device linked images are passed to the host link phase.
2704 class OpenMPActionBuilder final : public DeviceActionBuilder {
2705 /// The OpenMP actions for the current input.
2706 ActionList OpenMPDeviceActions;
2708 /// The linker inputs obtained for each toolchain.
2709 SmallVector<ActionList, 8> DeviceLinkerInputs;
2712 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2713 const Driver::InputList &Inputs)
2714 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2716 ActionBuilderReturnCode
2717 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2718 phases::ID CurPhase, phases::ID FinalPhase,
2719 PhasesTy &Phases) override {
2720 if (OpenMPDeviceActions.empty())
2721 return ABRT_Inactive;
2723 // We should always have an action for each input.
2724 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2725 "Number of OpenMP actions and toolchains do not match.");
2727 // The host only depends on device action in the linking phase, when all
2728 // the device images have to be embedded in the host image.
2729 if (CurPhase == phases::Link) {
2730 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2731 "Toolchains and linker inputs sizes do not match.");
2732 auto LI = DeviceLinkerInputs.begin();
2733 for (auto *A : OpenMPDeviceActions) {
2738 // We passed the device action as a host dependence, so we don't need to
2739 // do anything else with them.
2740 OpenMPDeviceActions.clear();
2741 return ABRT_Success;
2744 // By default, we produce an action for each device arch.
2745 for (Action *&A : OpenMPDeviceActions)
2746 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2748 return ABRT_Success;
2751 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2753 // If this is an input action replicate it for each OpenMP toolchain.
2754 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2755 OpenMPDeviceActions.clear();
2756 for (unsigned I = 0; I < ToolChains.size(); ++I)
2757 OpenMPDeviceActions.push_back(
2758 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2759 return ABRT_Success;
2762 // If this is an unbundling action use it as is for each OpenMP toolchain.
2763 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2764 OpenMPDeviceActions.clear();
2765 auto *IA = cast<InputAction>(UA->getInputs().back());
2766 std::string FileName = IA->getInputArg().getAsString(Args);
2767 // Check if the type of the file is the same as the action. Do not
2768 // unbundle it if it is not. Do not unbundle .so files, for example,
2769 // which are not object files.
2770 if (IA->getType() == types::TY_Object &&
2771 (!llvm::sys::path::has_extension(FileName) ||
2772 types::lookupTypeForExtension(
2773 llvm::sys::path::extension(FileName).drop_front()) !=
2775 return ABRT_Inactive;
2776 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2777 OpenMPDeviceActions.push_back(UA);
2778 UA->registerDependentActionInfo(
2779 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2781 return ABRT_Success;
2784 // When generating code for OpenMP we use the host compile phase result as
2785 // a dependence to the device compile phase so that it can learn what
2786 // declarations should be emitted. However, this is not the only use for
2787 // the host action, so we prevent it from being collapsed.
2788 if (isa<CompileJobAction>(HostAction)) {
2789 HostAction->setCannotBeCollapsedWithNextDependentAction();
2790 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2791 "Toolchains and device action sizes do not match.");
2792 OffloadAction::HostDependence HDep(
2793 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2794 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2795 auto TC = ToolChains.begin();
2796 for (Action *&A : OpenMPDeviceActions) {
2797 assert(isa<CompileJobAction>(A));
2798 OffloadAction::DeviceDependences DDep;
2799 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2800 A = C.MakeAction<OffloadAction>(HDep, DDep);
2804 return ABRT_Success;
2807 void appendTopLevelActions(ActionList &AL) override {
2808 if (OpenMPDeviceActions.empty())
2811 // We should always have an action for each input.
2812 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2813 "Number of OpenMP actions and toolchains do not match.");
2815 // Append all device actions followed by the proper offload action.
2816 auto TI = ToolChains.begin();
2817 for (auto *A : OpenMPDeviceActions) {
2818 OffloadAction::DeviceDependences Dep;
2819 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2820 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2823 // We no longer need the action stored in this builder.
2824 OpenMPDeviceActions.clear();
2827 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2828 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2829 "Toolchains and linker inputs sizes do not match.");
2831 // Append a new link action for each device.
2832 auto TC = ToolChains.begin();
2833 for (auto &LI : DeviceLinkerInputs) {
2834 auto *DeviceLinkAction =
2835 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2836 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2837 Action::OFK_OpenMP);
2842 bool initialize() override {
2843 // Get the OpenMP toolchains. If we don't get any, the action builder will
2844 // know there is nothing to do related to OpenMP offloading.
2845 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2846 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2848 ToolChains.push_back(TI->second);
2850 DeviceLinkerInputs.resize(ToolChains.size());
2854 bool canUseBundlerUnbundler() const override {
2855 // OpenMP should use bundled files whenever possible.
2861 /// TODO: Add the implementation for other specialized builders here.
2864 /// Specialized builders being used by this offloading action builder.
2865 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2867 /// Flag set to true if all valid builders allow file bundling/unbundling.
2871 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2872 const Driver::InputList &Inputs)
2874 // Create a specialized builder for each device toolchain.
2878 // Create a specialized builder for CUDA.
2879 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2881 // Create a specialized builder for HIP.
2882 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2884 // Create a specialized builder for OpenMP.
2885 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2888 // TODO: Build other specialized builders here.
2891 // Initialize all the builders, keeping track of errors. If all valid
2892 // builders agree that we can use bundling, set the flag to true.
2893 unsigned ValidBuilders = 0u;
2894 unsigned ValidBuildersSupportingBundling = 0u;
2895 for (auto *SB : SpecializedBuilders) {
2896 IsValid = IsValid && !SB->initialize();
2898 // Update the counters if the builder is valid.
2899 if (SB->isValid()) {
2901 if (SB->canUseBundlerUnbundler())
2902 ++ValidBuildersSupportingBundling;
2906 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
2909 ~OffloadingActionBuilder() {
2910 for (auto *SB : SpecializedBuilders)
2914 /// Generate an action that adds device dependences (if any) to a host action.
2915 /// If no device dependence actions exist, just return the host action \a
2916 /// HostAction. If an error is found or if no builder requires the host action
2917 /// to be generated, return nullptr.
2919 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2920 phases::ID CurPhase, phases::ID FinalPhase,
2921 DeviceActionBuilder::PhasesTy &Phases) {
2925 if (SpecializedBuilders.empty())
2928 assert(HostAction && "Invalid host action!");
2930 OffloadAction::DeviceDependences DDeps;
2931 // Check if all the programming models agree we should not emit the host
2932 // action. Also, keep track of the offloading kinds employed.
2933 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2934 unsigned InactiveBuilders = 0u;
2935 unsigned IgnoringBuilders = 0u;
2936 for (auto *SB : SpecializedBuilders) {
2937 if (!SB->isValid()) {
2943 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
2945 // If the builder explicitly says the host action should be ignored,
2946 // we need to increment the variable that tracks the builders that request
2947 // the host object to be ignored.
2948 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2951 // Unless the builder was inactive for this action, we have to record the
2952 // offload kind because the host will have to use it.
2953 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2954 OffloadKind |= SB->getAssociatedOffloadKind();
2957 // If all builders agree that the host object should be ignored, just return
2959 if (IgnoringBuilders &&
2960 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2963 if (DDeps.getActions().empty())
2966 // We have dependences we need to bundle together. We use an offload action
2968 OffloadAction::HostDependence HDep(
2969 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2970 /*BoundArch=*/nullptr, DDeps);
2971 return C.MakeAction<OffloadAction>(HDep, DDeps);
2974 /// Generate an action that adds a host dependence to a device action. The
2975 /// results will be kept in this action builder. Return true if an error was
2977 bool addHostDependenceToDeviceActions(Action *&HostAction,
2978 const Arg *InputArg) {
2982 // If we are supporting bundling/unbundling and the current action is an
2983 // input action of non-source file, we replace the host action by the
2984 // unbundling action. The bundler tool has the logic to detect if an input
2985 // is a bundle or not and if the input is not a bundle it assumes it is a
2986 // host file. Therefore it is safe to create an unbundling action even if
2987 // the input is not a bundle.
2988 if (CanUseBundler && isa<InputAction>(HostAction) &&
2989 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2990 !types::isSrcFile(HostAction->getType())) {
2991 auto UnbundlingHostAction =
2992 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2993 UnbundlingHostAction->registerDependentActionInfo(
2994 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2995 /*BoundArch=*/StringRef(), Action::OFK_Host);
2996 HostAction = UnbundlingHostAction;
2999 assert(HostAction && "Invalid host action!");
3001 // Register the offload kinds that are used.
3002 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3003 for (auto *SB : SpecializedBuilders) {
3007 auto RetCode = SB->addDeviceDepences(HostAction);
3009 // Host dependences for device actions are not compatible with that same
3010 // action being ignored.
3011 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3012 "Host dependence not expected to be ignored.!");
3014 // Unless the builder was inactive for this action, we have to record the
3015 // offload kind because the host will have to use it.
3016 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3017 OffloadKind |= SB->getAssociatedOffloadKind();
3020 // Do not use unbundler if the Host does not depend on device action.
3021 if (OffloadKind == Action::OFK_None && CanUseBundler)
3022 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3023 HostAction = UA->getInputs().back();
3028 /// Add the offloading top level actions to the provided action list. This
3029 /// function can replace the host action by a bundling action if the
3030 /// programming models allow it.
3031 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3032 const Arg *InputArg) {
3033 // Get the device actions to be appended.
3034 ActionList OffloadAL;
3035 for (auto *SB : SpecializedBuilders) {
3038 SB->appendTopLevelActions(OffloadAL);
3041 // If we can use the bundler, replace the host action by the bundling one in
3042 // the resulting list. Otherwise, just append the device actions. For
3043 // device only compilation, HostAction is a null pointer, therefore only do
3044 // this when HostAction is not a null pointer.
3045 if (CanUseBundler && HostAction && !OffloadAL.empty()) {
3046 // Add the host action to the list in order to create the bundling action.
3047 OffloadAL.push_back(HostAction);
3049 // We expect that the host action was just appended to the action list
3050 // before this method was called.
3051 assert(HostAction == AL.back() && "Host action not in the list??");
3052 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3053 AL.back() = HostAction;
3055 AL.append(OffloadAL.begin(), OffloadAL.end());
3057 // Propagate to the current host action (if any) the offload information
3058 // associated with the current input.
3060 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3061 /*BoundArch=*/nullptr);
3065 /// Processes the host linker action. This currently consists of replacing it
3066 /// with an offload action if there are device link objects and propagate to
3067 /// the host action all the offload kinds used in the current compilation. The
3068 /// resulting action is returned.
3069 Action *processHostLinkAction(Action *HostAction) {
3070 // Add all the dependences from the device linking actions.
3071 OffloadAction::DeviceDependences DDeps;
3072 for (auto *SB : SpecializedBuilders) {
3076 SB->appendLinkDependences(DDeps);
3079 // Calculate all the offload kinds used in the current compilation.
3080 unsigned ActiveOffloadKinds = 0u;
3081 for (auto &I : InputArgToOffloadKindMap)
3082 ActiveOffloadKinds |= I.second;
3084 // If we don't have device dependencies, we don't have to create an offload
3086 if (DDeps.getActions().empty()) {
3087 // Propagate all the active kinds to host action. Given that it is a link
3088 // action it is assumed to depend on all actions generated so far.
3089 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3090 /*BoundArch=*/nullptr);
3094 // Create the offload action with all dependences. When an offload action
3095 // is created the kinds are propagated to the host action, so we don't have
3096 // to do that explicitly here.
3097 OffloadAction::HostDependence HDep(
3098 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3099 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3100 return C.MakeAction<OffloadAction>(HDep, DDeps);
3103 } // anonymous namespace.
3105 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3106 const InputList &Inputs, ActionList &Actions) const {
3107 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3109 if (!SuppressMissingInputWarning && Inputs.empty()) {
3110 Diag(clang::diag::err_drv_no_input_files);
3115 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3117 if (FinalPhase == phases::Link) {
3118 if (Args.hasArg(options::OPT_emit_llvm))
3119 Diag(clang::diag::err_drv_emit_llvm_link);
3120 if (IsCLMode() && LTOMode != LTOK_None &&
3121 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3122 Diag(clang::diag::err_drv_lto_without_lld);
3125 // Reject -Z* at the top level, these options should never have been exposed
3127 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
3128 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
3130 // Diagnose misuse of /Fo.
3131 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3132 StringRef V = A->getValue();
3133 if (Inputs.size() > 1 && !V.empty() &&
3134 !llvm::sys::path::is_separator(V.back())) {
3135 // Check whether /Fo tries to name an output file for multiple inputs.
3136 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3137 << A->getSpelling() << V;
3138 Args.eraseArg(options::OPT__SLASH_Fo);
3142 // Diagnose misuse of /Fa.
3143 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3144 StringRef V = A->getValue();
3145 if (Inputs.size() > 1 && !V.empty() &&
3146 !llvm::sys::path::is_separator(V.back())) {
3147 // Check whether /Fa tries to name an asm file for multiple inputs.
3148 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3149 << A->getSpelling() << V;
3150 Args.eraseArg(options::OPT__SLASH_Fa);
3154 // Diagnose misuse of /o.
3155 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3156 if (A->getValue()[0] == '\0') {
3157 // It has to have a value.
3158 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3159 Args.eraseArg(options::OPT__SLASH_o);
3163 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3164 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3165 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3166 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3167 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3168 Args.eraseArg(options::OPT__SLASH_Yc);
3169 Args.eraseArg(options::OPT__SLASH_Yu);
3170 YcArg = YuArg = nullptr;
3172 if (YcArg && Inputs.size() > 1) {
3173 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3174 Args.eraseArg(options::OPT__SLASH_Yc);
3177 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3178 // If only preprocessing or /Y- is used, all pch handling is disabled.
3179 // Rather than check for it everywhere, just remove clang-cl pch-related
3181 Args.eraseArg(options::OPT__SLASH_Fp);
3182 Args.eraseArg(options::OPT__SLASH_Yc);
3183 Args.eraseArg(options::OPT__SLASH_Yu);
3184 YcArg = YuArg = nullptr;
3187 // Builder to be used to build offloading actions.
3188 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3190 // Construct the actions to perform.
3191 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3192 ActionList LinkerInputs;
3194 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
3195 for (auto &I : Inputs) {
3196 types::ID InputType = I.first;
3197 const Arg *InputArg = I.second;
3200 types::getCompilationPhases(InputType, PL);
3202 // If the first step comes after the final phase we are doing as part of
3203 // this compilation, warn the user about it.
3204 phases::ID InitialPhase = PL[0];
3205 if (InitialPhase > FinalPhase) {
3206 if (InputArg->isClaimed())
3209 // Claim here to avoid the more general unused warning.
3212 // Suppress all unused style warnings with -Qunused-arguments
3213 if (Args.hasArg(options::OPT_Qunused_arguments))
3216 // Special case when final phase determined by binary name, rather than
3217 // by a command-line argument with a corresponding Arg.
3219 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3220 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3221 // Special case '-E' warning on a previously preprocessed file to make
3223 else if (InitialPhase == phases::Compile &&
3224 FinalPhase == phases::Preprocess &&
3225 getPreprocessedType(InputType) == types::TY_INVALID)
3226 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3227 << InputArg->getAsString(Args) << !!FinalPhaseArg
3228 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3230 Diag(clang::diag::warn_drv_input_file_unused)
3231 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3233 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3238 // Add a separate precompile phase for the compile phase.
3239 if (FinalPhase >= phases::Compile) {
3240 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3241 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
3242 types::getCompilationPhases(HeaderType, PCHPL);
3243 // Build the pipeline for the pch file.
3244 Action *ClangClPch =
3245 C.MakeAction<InputAction>(*InputArg, HeaderType);
3246 for (phases::ID Phase : PCHPL)
3247 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3249 Actions.push_back(ClangClPch);
3250 // The driver currently exits after the first failed command. This
3251 // relies on that behavior, to make sure if the pch generation fails,
3252 // the main compilation won't run.
3253 // FIXME: If the main compilation fails, the PCH generation should
3254 // probably not be considered successful either.
3258 // Build the pipeline for this file.
3259 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3261 // Use the current host action in any of the offloading actions, if
3263 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3266 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3268 phases::ID Phase = *i;
3270 // We are done if this step is past what the user requested.
3271 if (Phase > FinalPhase)
3274 // Add any offload action the host action depends on.
3275 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3276 Current, InputArg, Phase, FinalPhase, PL);
3280 // Queue linker inputs.
3281 if (Phase == phases::Link) {
3282 assert((i + 1) == e && "linking must be final compilation step.");
3283 LinkerInputs.push_back(Current);
3288 // Each precompiled header file after a module file action is a module
3289 // header of that same module file, rather than being compiled to a
3291 if (Phase == phases::Precompile && HeaderModuleAction &&
3292 getPrecompiledType(InputType) == types::TY_PCH) {
3293 HeaderModuleAction->addModuleHeaderInput(Current);
3298 // FIXME: Should we include any prior module file outputs as inputs of
3299 // later actions in the same command line?
3301 // Otherwise construct the appropriate action.
3302 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3304 // We didn't create a new action, so we will just move to the next phase.
3305 if (NewCurrent == Current)
3308 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3309 HeaderModuleAction = HMA;
3311 Current = NewCurrent;
3313 // Use the current host action in any of the offloading actions, if
3315 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3318 if (Current->getType() == types::TY_Nothing)
3322 // If we ended with something, add to the output list.
3324 Actions.push_back(Current);
3326 // Add any top level actions generated for offloading.
3327 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3330 // Add a link action if necessary.
3331 if (!LinkerInputs.empty()) {
3332 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3333 LA = OffloadBuilder.processHostLinkAction(LA);
3334 Actions.push_back(LA);
3337 // If we are linking, claim any options which are obviously only used for
3339 if (FinalPhase == phases::Link && PL.size() == 1) {
3340 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3341 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3344 // Claim ignored clang-cl options.
3345 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3347 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3348 // to non-CUDA compilations and should not trigger warnings there.
3349 Args.ClaimAllArgs(options::OPT_cuda_host_only);
3350 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3353 Action *Driver::ConstructPhaseAction(
3354 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3355 Action::OffloadKind TargetDeviceOffloadKind) const {
3356 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3358 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3359 // encode this in the steps because the intermediate type depends on
3360 // arguments. Just special case here.
3361 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3364 // Build the appropriate action.
3367 llvm_unreachable("link action invalid here.");
3368 case phases::Preprocess: {
3370 // -{M, MM} alter the output type.
3371 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
3372 OutputTy = types::TY_Dependencies;
3374 OutputTy = Input->getType();
3375 if (!Args.hasFlag(options::OPT_frewrite_includes,
3376 options::OPT_fno_rewrite_includes, false) &&
3377 !Args.hasFlag(options::OPT_frewrite_imports,
3378 options::OPT_fno_rewrite_imports, false) &&
3380 OutputTy = types::getPreprocessedType(OutputTy);
3381 assert(OutputTy != types::TY_INVALID &&
3382 "Cannot preprocess this input type!");
3384 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3386 case phases::Precompile: {
3387 types::ID OutputTy = getPrecompiledType(Input->getType());
3388 assert(OutputTy != types::TY_INVALID &&
3389 "Cannot precompile this input type!");
3391 // If we're given a module name, precompile header file inputs as a
3392 // module, not as a precompiled header.
3393 const char *ModName = nullptr;
3394 if (OutputTy == types::TY_PCH) {
3395 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3396 ModName = A->getValue();
3398 OutputTy = types::TY_ModuleFile;
3401 if (Args.hasArg(options::OPT_fsyntax_only)) {
3402 // Syntax checks should not emit a PCH file
3403 OutputTy = types::TY_Nothing;
3407 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3409 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3411 case phases::Compile: {
3412 if (Args.hasArg(options::OPT_fsyntax_only))
3413 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3414 if (Args.hasArg(options::OPT_rewrite_objc))
3415 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3416 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3417 return C.MakeAction<CompileJobAction>(Input,
3418 types::TY_RewrittenLegacyObjC);
3419 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
3420 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3421 if (Args.hasArg(options::OPT__migrate))
3422 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3423 if (Args.hasArg(options::OPT_emit_ast))
3424 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3425 if (Args.hasArg(options::OPT_module_file_info))
3426 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3427 if (Args.hasArg(options::OPT_verify_pch))
3428 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3429 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3431 case phases::Backend: {
3432 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
3434 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
3435 return C.MakeAction<BackendJobAction>(Input, Output);
3437 if (Args.hasArg(options::OPT_emit_llvm)) {
3439 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
3440 return C.MakeAction<BackendJobAction>(Input, Output);
3442 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
3444 case phases::Assemble:
3445 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
3448 llvm_unreachable("invalid phase in ConstructPhaseAction");
3451 void Driver::BuildJobs(Compilation &C) const {
3452 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3454 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3456 // It is an error to provide a -o option if we are making multiple output
3459 unsigned NumOutputs = 0;
3460 for (const Action *A : C.getActions())
3461 if (A->getType() != types::TY_Nothing)
3464 if (NumOutputs > 1) {
3465 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
3466 FinalOutput = nullptr;
3470 // Collect the list of architectures.
3471 llvm::StringSet<> ArchNames;
3472 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3473 for (const Arg *A : C.getArgs())
3474 if (A->getOption().matches(options::OPT_arch))
3475 ArchNames.insert(A->getValue());
3477 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3478 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
3479 for (Action *A : C.getActions()) {
3480 // If we are linking an image for multiple archs then the linker wants
3481 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3482 // doesn't fit in cleanly because we have to pass this information down.
3484 // FIXME: This is a hack; find a cleaner way to integrate this into the
3486 const char *LinkingOutput = nullptr;
3487 if (isa<LipoJobAction>(A)) {
3489 LinkingOutput = FinalOutput->getValue();
3491 LinkingOutput = getDefaultImageName();
3494 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
3495 /*BoundArch*/ StringRef(),
3496 /*AtTopLevel*/ true,
3497 /*MultipleArchs*/ ArchNames.size() > 1,
3498 /*LinkingOutput*/ LinkingOutput, CachedResults,
3499 /*TargetDeviceOffloadKind*/ Action::OFK_None);
3502 // If the user passed -Qunused-arguments or there were errors, don't warn
3503 // about any unused arguments.
3504 if (Diags.hasErrorOccurred() ||
3505 C.getArgs().hasArg(options::OPT_Qunused_arguments))
3509 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
3511 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
3512 (void)C.getArgs().hasArg(options::OPT_driver_mode);
3513 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
3515 for (Arg *A : C.getArgs()) {
3516 // FIXME: It would be nice to be able to send the argument to the
3517 // DiagnosticsEngine, so that extra values, position, and so on could be
3519 if (!A->isClaimed()) {
3520 if (A->getOption().hasFlag(options::NoArgumentUnused))
3523 // Suppress the warning automatically if this is just a flag, and it is an
3524 // instance of an argument we already claimed.
3525 const Option &Opt = A->getOption();
3526 if (Opt.getKind() == Option::FlagClass) {
3527 bool DuplicateClaimed = false;
3529 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3530 if (AA->isClaimed()) {
3531 DuplicateClaimed = true;
3536 if (DuplicateClaimed)
3540 // In clang-cl, don't mention unknown arguments here since they have
3541 // already been warned about.
3542 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3543 Diag(clang::diag::warn_drv_unused_argument)
3544 << A->getAsString(C.getArgs());
3550 /// Utility class to control the collapse of dependent actions and select the
3551 /// tools accordingly.
3552 class ToolSelector final {
3553 /// The tool chain this selector refers to.
3554 const ToolChain &TC;
3556 /// The compilation this selector refers to.
3557 const Compilation &C;
3559 /// The base action this selector refers to.
3560 const JobAction *BaseAction;
3562 /// Set to true if the current toolchain refers to host actions.
3563 bool IsHostSelector;
3565 /// Set to true if save-temps and embed-bitcode functionalities are active.
3569 /// Get previous dependent action or null if that does not exist. If
3570 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3571 /// null will be returned.
3572 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3573 ActionList &SavedOffloadAction,
3574 bool CanBeCollapsed = true) {
3575 // An option can be collapsed only if it has a single input.
3576 if (Inputs.size() != 1)
3579 Action *CurAction = *Inputs.begin();
3580 if (CanBeCollapsed &&
3581 !CurAction->isCollapsingWithNextDependentActionLegal())
3584 // If the input action is an offload action. Look through it and save any
3585 // offload action that can be dropped in the event of a collapse.
3586 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3587 // If the dependent action is a device action, we will attempt to collapse
3588 // only with other device actions. Otherwise, we would do the same but
3589 // with host actions only.
3590 if (!IsHostSelector) {
3591 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3593 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3594 if (CanBeCollapsed &&
3595 !CurAction->isCollapsingWithNextDependentActionLegal())
3597 SavedOffloadAction.push_back(OA);
3598 return dyn_cast<JobAction>(CurAction);
3600 } else if (OA->hasHostDependence()) {
3601 CurAction = OA->getHostDependence();
3602 if (CanBeCollapsed &&
3603 !CurAction->isCollapsingWithNextDependentActionLegal())
3605 SavedOffloadAction.push_back(OA);
3606 return dyn_cast<JobAction>(CurAction);
3611 return dyn_cast<JobAction>(CurAction);
3614 /// Return true if an assemble action can be collapsed.
3615 bool canCollapseAssembleAction() const {
3616 return TC.useIntegratedAs() && !SaveTemps &&
3617 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3618 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3619 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3622 /// Return true if a preprocessor action can be collapsed.
3623 bool canCollapsePreprocessorAction() const {
3624 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3625 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3626 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3629 /// Struct that relates an action with the offload actions that would be
3630 /// collapsed with it.
3631 struct JobActionInfo final {
3632 /// The action this info refers to.
3633 const JobAction *JA = nullptr;
3634 /// The offload actions we need to take care off if this action is
3636 ActionList SavedOffloadAction;
3639 /// Append collapsed offload actions from the give nnumber of elements in the
3640 /// action info array.
3641 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3642 ArrayRef<JobActionInfo> &ActionInfo,
3643 unsigned ElementNum) {
3644 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3645 for (unsigned I = 0; I < ElementNum; ++I)
3646 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3647 ActionInfo[I].SavedOffloadAction.end());
3650 /// Functions that attempt to perform the combining. They detect if that is
3651 /// legal, and if so they update the inputs \a Inputs and the offload action
3652 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3653 /// the combined action is returned. If the combining is not legal or if the
3654 /// tool does not exist, null is returned.
3655 /// Currently three kinds of collapsing are supported:
3656 /// - Assemble + Backend + Compile;
3657 /// - Assemble + Backend ;
3658 /// - Backend + Compile.
3660 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3662 ActionList &CollapsedOffloadAction) {
3663 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3665 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3666 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3667 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3668 if (!AJ || !BJ || !CJ)
3671 // Get compiler tool.
3672 const Tool *T = TC.SelectTool(*CJ);
3676 // When using -fembed-bitcode, it is required to have the same tool (clang)
3677 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3679 const Tool *BT = TC.SelectTool(*BJ);
3684 if (!T->hasIntegratedAssembler())
3687 Inputs = CJ->getInputs();
3688 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3692 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3694 ActionList &CollapsedOffloadAction) {
3695 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3697 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3698 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3702 // Retrieve the compile job, backend action must always be preceded by one.
3703 ActionList CompileJobOffloadActions;
3704 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3705 /*CanBeCollapsed=*/false);
3706 if (!AJ || !BJ || !CJ)
3709 assert(isa<CompileJobAction>(CJ) &&
3710 "Expecting compile job preceding backend job.");
3712 // Get compiler tool.
3713 const Tool *T = TC.SelectTool(*CJ);
3717 if (!T->hasIntegratedAssembler())
3720 Inputs = BJ->getInputs();
3721 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3725 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3727 ActionList &CollapsedOffloadAction) {
3728 if (ActionInfo.size() < 2)
3730 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3731 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3735 // Check if the initial input (to the compile job or its predessor if one
3736 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3737 // and we can still collapse the compile and backend jobs when we have
3738 // -save-temps. I.e. there is no need for a separate compile job just to
3739 // emit unoptimized bitcode.
3740 bool InputIsBitcode = true;
3741 for (size_t i = 1; i < ActionInfo.size(); i++)
3742 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3743 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3744 InputIsBitcode = false;
3747 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3750 // Get compiler tool.
3751 const Tool *T = TC.SelectTool(*CJ);
3755 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
3758 Inputs = CJ->getInputs();
3759 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3764 /// Updates the inputs if the obtained tool supports combining with
3765 /// preprocessor action, and the current input is indeed a preprocessor
3766 /// action. If combining results in the collapse of offloading actions, those
3767 /// are appended to \a CollapsedOffloadAction.
3768 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
3769 ActionList &CollapsedOffloadAction) {
3770 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3773 // Attempt to get a preprocessor action dependence.
3774 ActionList PreprocessJobOffloadActions;
3775 ActionList NewInputs;
3776 for (Action *A : Inputs) {
3777 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
3778 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
3779 NewInputs.push_back(A);
3783 // This is legal to combine. Append any offload action we found and add the
3784 // current input to preprocessor inputs.
3785 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3786 PreprocessJobOffloadActions.end());
3787 NewInputs.append(PJ->input_begin(), PJ->input_end());
3793 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3794 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3795 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3796 EmbedBitcode(EmbedBitcode) {
3797 assert(BaseAction && "Invalid base action.");
3798 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3801 /// Check if a chain of actions can be combined and return the tool that can
3802 /// handle the combination of actions. The pointer to the current inputs \a
3803 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3804 /// connected to collapsed actions are updated accordingly. The latter enables
3805 /// the caller of the selector to process them afterwards instead of just
3806 /// dropping them. If no suitable tool is found, null will be returned.
3807 const Tool *getTool(ActionList &Inputs,
3808 ActionList &CollapsedOffloadAction) {
3810 // Get the largest chain of actions that we could combine.
3813 SmallVector<JobActionInfo, 5> ActionChain(1);
3814 ActionChain.back().JA = BaseAction;
3815 while (ActionChain.back().JA) {
3816 const Action *CurAction = ActionChain.back().JA;
3818 // Grow the chain by one element.
3819 ActionChain.resize(ActionChain.size() + 1);
3820 JobActionInfo &AI = ActionChain.back();
3822 // Attempt to fill it with the
3824 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
3827 // Pop the last action info as it could not be filled.
3828 ActionChain.pop_back();
3831 // Attempt to combine actions. If all combining attempts failed, just return
3832 // the tool of the provided action. At the end we attempt to combine the
3833 // action with any preprocessor action it may depend on.
3836 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3837 CollapsedOffloadAction);
3839 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3841 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3843 Inputs = BaseAction->getInputs();
3844 T = TC.SelectTool(*BaseAction);
3847 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3853 /// Return a string that uniquely identifies the result of a job. The bound arch
3854 /// is not necessarily represented in the toolchain's triple -- for example,
3855 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
3856 /// Also, we need to add the offloading device kind, as the same tool chain can
3857 /// be used for host and device for some programming models, e.g. OpenMP.
3858 static std::string GetTriplePlusArchString(const ToolChain *TC,
3859 StringRef BoundArch,
3860 Action::OffloadKind OffloadKind) {
3861 std::string TriplePlusArch = TC->getTriple().normalize();
3862 if (!BoundArch.empty()) {
3863 TriplePlusArch += "-";
3864 TriplePlusArch += BoundArch;
3866 TriplePlusArch += "-";
3867 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3868 return TriplePlusArch;
3871 InputInfo Driver::BuildJobsForAction(
3872 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3873 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3874 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3875 Action::OffloadKind TargetDeviceOffloadKind) const {
3876 std::pair<const Action *, std::string> ActionTC = {
3877 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3878 auto CachedResult = CachedResults.find(ActionTC);
3879 if (CachedResult != CachedResults.end()) {
3880 return CachedResult->second;
3882 InputInfo Result = BuildJobsForActionNoCache(
3883 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
3884 CachedResults, TargetDeviceOffloadKind);
3885 CachedResults[ActionTC] = Result;
3889 InputInfo Driver::BuildJobsForActionNoCache(
3890 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3891 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3892 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3893 Action::OffloadKind TargetDeviceOffloadKind) const {
3894 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3896 InputInfoList OffloadDependencesInputInfo;
3897 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
3898 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3899 // The 'Darwin' toolchain is initialized only when its arguments are
3900 // computed. Get the default arguments for OFK_None to ensure that
3901 // initialization is performed before processing the offload action.
3902 // FIXME: Remove when darwin's toolchain is initialized during construction.
3903 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3905 // The offload action is expected to be used in four different situations.
3907 // a) Set a toolchain/architecture/kind for a host action:
3908 // Host Action 1 -> OffloadAction -> Host Action 2
3910 // b) Set a toolchain/architecture/kind for a device action;
3911 // Device Action 1 -> OffloadAction -> Device Action 2
3913 // c) Specify a device dependence to a host action;
3914 // Device Action 1 _
3916 // Host Action 1 ---> OffloadAction -> Host Action 2
3918 // d) Specify a host dependence to a device action.
3921 // Device Action 1 ---> OffloadAction -> Device Action 2
3923 // For a) and b), we just return the job generated for the dependence. For
3924 // c) and d) we override the current action with the host/device dependence
3925 // if the current toolchain is host/device and set the offload dependences
3926 // info with the jobs obtained from the device/host dependence(s).
3928 // If there is a single device option, just generate the job for it.
3929 if (OA->hasSingleDeviceDependence()) {
3931 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3932 const char *DepBoundArch) {
3934 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3935 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
3936 CachedResults, DepA->getOffloadingDeviceKind());
3941 // If 'Action 2' is host, we generate jobs for the device dependences and
3942 // override the current action with the host dependence. Otherwise, we
3943 // generate the host dependences and override the action with the device
3944 // dependence. The dependences can't therefore be a top-level action.
3945 OA->doOnEachDependence(
3946 /*IsHostDependence=*/BuildingForOffloadDevice,
3947 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3948 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3949 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3950 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
3951 DepA->getOffloadingDeviceKind()));
3954 A = BuildingForOffloadDevice
3955 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3956 : OA->getHostDependence();
3959 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
3960 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3961 // just using Args was better?
3962 const Arg &Input = IA->getInputArg();
3964 if (Input.getOption().matches(options::OPT_INPUT)) {
3965 const char *Name = Input.getValue();
3966 return InputInfo(A, Name, /* BaseInput = */ Name);
3968 return InputInfo(A, &Input, /* BaseInput = */ "");
3971 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
3972 const ToolChain *TC;
3973 StringRef ArchName = BAA->getArchName();
3975 if (!ArchName.empty())
3976 TC = &getToolChain(C.getArgs(),
3977 computeTargetTriple(*this, TargetTriple,
3978 C.getArgs(), ArchName));
3980 TC = &C.getDefaultToolChain();
3982 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
3983 MultipleArchs, LinkingOutput, CachedResults,
3984 TargetDeviceOffloadKind);
3988 ActionList Inputs = A->getInputs();
3990 const JobAction *JA = cast<JobAction>(A);
3991 ActionList CollapsedOffloadActions;
3993 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3994 embedBitcodeInObject() && !isUsingLTO());
3995 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4000 // If we've collapsed action list that contained OffloadAction we
4001 // need to build jobs for host/device-side inputs it may have held.
4002 for (const auto *OA : CollapsedOffloadActions)
4003 cast<OffloadAction>(OA)->doOnEachDependence(
4004 /*IsHostDependence=*/BuildingForOffloadDevice,
4005 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4006 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4007 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
4008 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
4009 DepA->getOffloadingDeviceKind()));
4012 // Only use pipes when there is exactly one input.
4013 InputInfoList InputInfos;
4014 for (const Action *Input : Inputs) {
4015 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4016 // shouldn't get temporary output names.
4017 // FIXME: Clean this up.
4018 bool SubJobAtTopLevel =
4019 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
4020 InputInfos.push_back(BuildJobsForAction(
4021 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
4022 CachedResults, A->getOffloadingDeviceKind()));
4025 // Always use the first input as the base input.
4026 const char *BaseInput = InputInfos[0].getBaseInput();
4028 // ... except dsymutil actions, which use their actual input as the base
4030 if (JA->getType() == types::TY_dSYM)
4031 BaseInput = InputInfos[0].getFilename();
4033 // ... and in header module compilations, which use the module name.
4034 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4035 BaseInput = ModuleJA->getModuleName();
4037 // Append outputs of offload device jobs to the input list
4038 if (!OffloadDependencesInputInfo.empty())
4039 InputInfos.append(OffloadDependencesInputInfo.begin(),
4040 OffloadDependencesInputInfo.end());
4042 // Set the effective triple of the toolchain for the duration of this job.
4043 llvm::Triple EffectiveTriple;
4044 const ToolChain &ToolTC = T->getToolChain();
4045 const ArgList &Args =
4046 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
4047 if (InputInfos.size() != 1) {
4048 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4050 // Pass along the input type if it can be unambiguously determined.
4051 EffectiveTriple = llvm::Triple(
4052 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4054 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4056 // Determine the place to write output to, if any.
4058 InputInfoList UnbundlingResults;
4059 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4060 // If we have an unbundling job, we need to create results for all the
4061 // outputs. We also update the results cache so that other actions using
4062 // this unbundling action can get the right results.
4063 for (auto &UI : UA->getDependentActionsInfo()) {
4064 assert(UI.DependentOffloadKind != Action::OFK_None &&
4065 "Unbundling with no offloading??");
4067 // Unbundling actions are never at the top level. When we generate the
4068 // offloading prefix, we also do that for the host file because the
4069 // unbundling action does not change the type of the output which can
4070 // cause a overwrite.
4071 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4072 UI.DependentOffloadKind,
4073 UI.DependentToolChain->getTriple().normalize(),
4074 /*CreatePrefixForHost=*/true);
4075 auto CurI = InputInfo(
4077 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4078 /*AtTopLevel=*/false,
4080 UI.DependentOffloadKind == Action::OFK_HIP,
4083 // Save the unbundling result.
4084 UnbundlingResults.push_back(CurI);
4086 // Get the unique string identifier for this dependence and cache the
4089 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4090 if (UI.DependentOffloadKind == Action::OFK_Host)
4093 Arch = UI.DependentBoundArch;
4097 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4098 UI.DependentOffloadKind)}] =
4102 // Now that we have all the results generated, select the one that should be
4103 // returned for the current depending action.
4104 std::pair<const Action *, std::string> ActionTC = {
4105 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4106 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4107 "Result does not exist??");
4108 Result = CachedResults[ActionTC];
4109 } else if (JA->getType() == types::TY_Nothing)
4110 Result = InputInfo(A, BaseInput);
4112 // We only have to generate a prefix for the host if this is not a top-level
4114 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4115 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4116 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4118 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
4119 AtTopLevel, MultipleArchs,
4124 if (CCCPrintBindings && !CCGenDiagnostics) {
4125 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4126 << " - \"" << T->getName() << "\", inputs: [";
4127 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4128 llvm::errs() << InputInfos[i].getAsString();
4130 llvm::errs() << ", ";
4132 if (UnbundlingResults.empty())
4133 llvm::errs() << "], output: " << Result.getAsString() << "\n";
4135 llvm::errs() << "], outputs: [";
4136 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4137 llvm::errs() << UnbundlingResults[i].getAsString();
4139 llvm::errs() << ", ";
4141 llvm::errs() << "] \n";
4144 if (UnbundlingResults.empty())
4146 C, *JA, Result, InputInfos,
4147 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4150 T->ConstructJobMultipleOutputs(
4151 C, *JA, UnbundlingResults, InputInfos,
4152 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4158 const char *Driver::getDefaultImageName() const {
4159 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4160 return Target.isOSWindows() ? "a.exe" : "a.out";
4163 /// Create output filename based on ArgValue, which could either be a
4164 /// full filename, filename without extension, or a directory. If ArgValue
4165 /// does not provide a filename, then use BaseName, and use the extension
4166 /// suitable for FileType.
4167 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
4169 types::ID FileType) {
4170 SmallString<128> Filename = ArgValue;
4172 if (ArgValue.empty()) {
4173 // If the argument is empty, output to BaseName in the current dir.
4174 Filename = BaseName;
4175 } else if (llvm::sys::path::is_separator(Filename.back())) {
4176 // If the argument is a directory, output to BaseName in that dir.
4177 llvm::sys::path::append(Filename, BaseName);
4180 if (!llvm::sys::path::has_extension(ArgValue)) {
4181 // If the argument didn't provide an extension, then set it.
4182 const char *Extension = types::getTypeTempSuffix(FileType, true);
4184 if (FileType == types::TY_Image &&
4185 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4186 // The output file is a dll.
4190 llvm::sys::path::replace_extension(Filename, Extension);
4193 return Args.MakeArgString(Filename.c_str());
4196 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
4197 const char *BaseInput,
4198 StringRef BoundArch, bool AtTopLevel,
4200 StringRef OffloadingPrefix) const {
4201 llvm::PrettyStackTraceString CrashInfo("Computing output path");
4202 // Output to a user requested destination?
4203 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
4204 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4205 return C.addResultFile(FinalOutput->getValue(), &JA);
4208 // For /P, preprocess to file named after BaseInput.
4209 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4210 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4211 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4213 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
4214 NameArg = A->getValue();
4215 return C.addResultFile(
4216 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4220 // Default to writing to stdout?
4221 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
4224 // Is this the assembly listing for /FA?
4225 if (JA.getType() == types::TY_PP_Asm &&
4226 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4227 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4228 // Use /Fa and the input filename to determine the asm file name.
4229 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4230 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4231 return C.addResultFile(
4232 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4236 // Output to a temporary file?
4237 if ((!AtTopLevel && !isSaveTempsEnabled() &&
4238 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4240 StringRef Name = llvm::sys::path::filename(BaseInput);
4241 std::pair<StringRef, StringRef> Split = Name.split('.');
4242 SmallString<128> TmpName;
4243 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4244 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4245 if (CCGenDiagnostics && A) {
4246 SmallString<128> CrashDirectory(A->getValue());
4247 llvm::sys::path::append(CrashDirectory, Split.first);
4248 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4249 std::error_code EC =
4250 llvm::sys::fs::createUniqueFile(CrashDirectory + Middle + Suffix, TmpName);
4252 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4256 TmpName = GetTemporaryPath(Split.first, Suffix);
4258 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4261 SmallString<128> BasePath(BaseInput);
4264 // Dsymutil actions should use the full path.
4265 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
4266 BaseName = BasePath;
4268 BaseName = llvm::sys::path::filename(BasePath);
4270 // Determine what the derived output name should be.
4271 const char *NamedOutput;
4273 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
4274 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4275 // The /Fo or /o flag decides the object filename.
4278 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4281 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4282 } else if (JA.getType() == types::TY_Image &&
4283 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4284 options::OPT__SLASH_o)) {
4285 // The /Fe or /o flag names the linked file.
4288 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4291 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
4292 } else if (JA.getType() == types::TY_Image) {
4294 // clang-cl uses BaseName for the executable name.
4296 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
4298 SmallString<128> Output(getDefaultImageName());
4299 Output += OffloadingPrefix;
4300 if (MultipleArchs && !BoundArch.empty()) {
4302 Output.append(BoundArch);
4304 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
4306 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
4307 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
4309 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4310 assert(Suffix && "All types used for output should have a suffix.");
4312 std::string::size_type End = std::string::npos;
4313 if (!types::appendSuffixForType(JA.getType()))
4314 End = BaseName.rfind('.');
4315 SmallString<128> Suffixed(BaseName.substr(0, End));
4316 Suffixed += OffloadingPrefix;
4317 if (MultipleArchs && !BoundArch.empty()) {
4319 Suffixed.append(BoundArch);
4321 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4322 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4323 // optimized bitcode output.
4324 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4325 JA.getType() == types::TY_LLVM_BC)
4329 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4332 // Prepend object file path if -save-temps=obj
4333 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4334 JA.getType() != types::TY_PCH) {
4335 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4336 SmallString<128> TempPath(FinalOutput->getValue());
4337 llvm::sys::path::remove_filename(TempPath);
4338 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4339 llvm::sys::path::append(TempPath, OutputFileName);
4340 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4343 // If we're saving temps and the temp file conflicts with the input file,
4344 // then avoid overwriting input file.
4345 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
4346 bool SameFile = false;
4347 SmallString<256> Result;
4348 llvm::sys::fs::current_path(Result);
4349 llvm::sys::path::append(Result, BaseName);
4350 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4351 // Must share the same path to conflict.
4353 StringRef Name = llvm::sys::path::filename(BaseInput);
4354 std::pair<StringRef, StringRef> Split = Name.split('.');
4355 std::string TmpName = GetTemporaryPath(
4356 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
4357 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4361 // As an annoying special case, PCH generation doesn't strip the pathname.
4362 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
4363 llvm::sys::path::remove_filename(BasePath);
4364 if (BasePath.empty())
4365 BasePath = NamedOutput;
4367 llvm::sys::path::append(BasePath, NamedOutput);
4368 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
4370 return C.addResultFile(NamedOutput, &JA);
4374 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
4375 // Search for Name in a list of paths.
4376 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4377 -> llvm::Optional<std::string> {
4378 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4379 // attempting to use this prefix when looking for file paths.
4380 for (const auto &Dir : P) {
4383 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4384 llvm::sys::path::append(P, Name);
4385 if (llvm::sys::fs::exists(Twine(P)))
4386 return P.str().str();
4391 if (auto P = SearchPaths(PrefixDirs))
4394 SmallString<128> R(ResourceDir);
4395 llvm::sys::path::append(R, Name);
4396 if (llvm::sys::fs::exists(Twine(R)))
4399 SmallString<128> P(TC.getCompilerRTPath());
4400 llvm::sys::path::append(P, Name);
4401 if (llvm::sys::fs::exists(Twine(P)))
4404 if (auto P = SearchPaths(TC.getLibraryPaths()))
4407 if (auto P = SearchPaths(TC.getFilePaths()))
4413 void Driver::generatePrefixedToolNames(
4414 StringRef Tool, const ToolChain &TC,
4415 SmallVectorImpl<std::string> &Names) const {
4416 // FIXME: Needs a better variable than TargetTriple
4417 Names.emplace_back((TargetTriple + "-" + Tool).str());
4418 Names.emplace_back(Tool);
4420 // Allow the discovery of tools prefixed with LLVM's default target triple.
4421 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4422 if (DefaultTargetTriple != TargetTriple)
4423 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
4426 static bool ScanDirForExecutable(SmallString<128> &Dir,
4427 ArrayRef<std::string> Names) {
4428 for (const auto &Name : Names) {
4429 llvm::sys::path::append(Dir, Name);
4430 if (llvm::sys::fs::can_execute(Twine(Dir)))
4432 llvm::sys::path::remove_filename(Dir);
4437 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
4438 SmallVector<std::string, 2> TargetSpecificExecutables;
4439 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4441 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4442 // attempting to use this prefix when looking for program paths.
4443 for (const auto &PrefixDir : PrefixDirs) {
4444 if (llvm::sys::fs::is_directory(PrefixDir)) {
4445 SmallString<128> P(PrefixDir);
4446 if (ScanDirForExecutable(P, TargetSpecificExecutables))
4449 SmallString<128> P((PrefixDir + Name).str());
4450 if (llvm::sys::fs::can_execute(Twine(P)))
4455 const ToolChain::path_list &List = TC.getProgramPaths();
4456 for (const auto &Path : List) {
4457 SmallString<128> P(Path);
4458 if (ScanDirForExecutable(P, TargetSpecificExecutables))
4462 // If all else failed, search the path.
4463 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4464 if (llvm::ErrorOr<std::string> P =
4465 llvm::sys::findProgramByName(TargetSpecificExecutable))
4471 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
4472 SmallString<128> Path;
4473 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
4475 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4482 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
4483 SmallString<128> Path;
4484 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
4486 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4493 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4494 SmallString<128> Output;
4495 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4496 // FIXME: If anybody needs it, implement this obscure rule:
4497 // "If you specify a directory without a file name, the default file name
4498 // is VCx0.pch., where x is the major version of Visual C++ in use."
4499 Output = FpArg->getValue();
4501 // "If you do not specify an extension as part of the path name, an
4502 // extension of .pch is assumed. "
4503 if (!llvm::sys::path::has_extension(Output))
4506 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4507 Output = YcArg->getValue();
4510 llvm::sys::path::replace_extension(Output, ".pch");
4512 return Output.str();
4515 const ToolChain &Driver::getToolChain(const ArgList &Args,
4516 const llvm::Triple &Target) const {
4518 auto &TC = ToolChains[Target.str()];
4520 switch (Target.getOS()) {
4521 case llvm::Triple::Haiku:
4522 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
4524 case llvm::Triple::Ananas:
4525 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4527 case llvm::Triple::CloudABI:
4528 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
4530 case llvm::Triple::Darwin:
4531 case llvm::Triple::MacOSX:
4532 case llvm::Triple::IOS:
4533 case llvm::Triple::TvOS:
4534 case llvm::Triple::WatchOS:
4535 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
4537 case llvm::Triple::DragonFly:
4538 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
4540 case llvm::Triple::OpenBSD:
4541 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
4543 case llvm::Triple::NetBSD:
4544 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
4546 case llvm::Triple::FreeBSD:
4547 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
4549 case llvm::Triple::Minix:
4550 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
4552 case llvm::Triple::Linux:
4553 case llvm::Triple::ELFIAMCU:
4554 if (Target.getArch() == llvm::Triple::hexagon)
4555 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4557 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4558 !Target.hasEnvironment())
4559 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4562 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
4564 case llvm::Triple::NaCl:
4565 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
4567 case llvm::Triple::Fuchsia:
4568 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
4570 case llvm::Triple::Solaris:
4571 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
4573 case llvm::Triple::AMDHSA:
4574 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
4576 case llvm::Triple::Win32:
4577 switch (Target.getEnvironment()) {
4579 if (Target.isOSBinFormatELF())
4580 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4581 else if (Target.isOSBinFormatMachO())
4582 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
4584 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4586 case llvm::Triple::GNU:
4587 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
4589 case llvm::Triple::Itanium:
4590 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4593 case llvm::Triple::MSVC:
4594 case llvm::Triple::UnknownEnvironment:
4595 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4596 .startswith_lower("bfd"))
4597 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4598 *this, Target, Args);
4601 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
4605 case llvm::Triple::PS4:
4606 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
4608 case llvm::Triple::Contiki:
4609 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
4611 case llvm::Triple::Hurd:
4612 TC = llvm::make_unique<toolchains::Hurd>(*this, Target, Args);
4615 // Of these targets, Hexagon is the only one that might have
4616 // an OS of Linux, in which case it got handled above already.
4617 switch (Target.getArch()) {
4618 case llvm::Triple::tce:
4619 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
4621 case llvm::Triple::tcele:
4622 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
4624 case llvm::Triple::hexagon:
4625 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4628 case llvm::Triple::lanai:
4629 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
4631 case llvm::Triple::xcore:
4632 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
4634 case llvm::Triple::wasm32:
4635 case llvm::Triple::wasm64:
4636 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
4638 case llvm::Triple::avr:
4639 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
4641 case llvm::Triple::msp430:
4643 llvm::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
4645 case llvm::Triple::riscv32:
4646 case llvm::Triple::riscv64:
4647 TC = llvm::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
4650 if (Target.getVendor() == llvm::Triple::Myriad)
4651 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4653 else if (toolchains::BareMetal::handlesTarget(Target))
4654 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
4655 else if (Target.isOSBinFormatELF())
4656 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4657 else if (Target.isOSBinFormatMachO())
4658 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
4660 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4665 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4666 // compiles always need two toolchains, the CUDA toolchain and the host
4667 // toolchain. So the only valid way to create a CUDA toolchain is via
4668 // CreateOffloadingDeviceToolChains.
4673 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
4674 // Say "no" if there is not exactly one input of a type clang understands.
4675 if (JA.size() != 1 ||
4676 !types::isAcceptedByClang((*JA.input_begin())->getType()))
4679 // And say "no" if this is not a kind of action clang understands.
4680 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
4681 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
4687 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4688 /// grouped values as integers. Numbers which are not provided are set to 0.
4690 /// \return True if the entire string was parsed (9.2), or all groups were
4691 /// parsed (10.3.5extrastuff).
4692 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4693 unsigned &Micro, bool &HadExtra) {
4696 Major = Minor = Micro = 0;
4700 if (Str.consumeInteger(10, Major))
4707 Str = Str.drop_front(1);
4709 if (Str.consumeInteger(10, Minor))
4715 Str = Str.drop_front(1);
4717 if (Str.consumeInteger(10, Micro))
4724 /// Parse digits from a string \p Str and fulfill \p Digits with
4725 /// the parsed numbers. This method assumes that the max number of
4726 /// digits to look for is equal to Digits.size().
4728 /// \return True if the entire string was parsed and there are
4729 /// no extra characters remaining at the end.
4730 bool Driver::GetReleaseVersion(StringRef Str,
4731 MutableArrayRef<unsigned> Digits) {
4735 unsigned CurDigit = 0;
4736 while (CurDigit < Digits.size()) {
4738 if (Str.consumeInteger(10, Digit))
4740 Digits[CurDigit] = Digit;
4745 Str = Str.drop_front(1);
4749 // More digits than requested, bail out...
4753 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
4754 unsigned IncludedFlagsBitmask = 0;
4755 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
4757 if (IsClCompatMode) {
4758 // Include CL and Core options.
4759 IncludedFlagsBitmask |= options::CLOption;
4760 IncludedFlagsBitmask |= options::CoreOption;
4762 ExcludedFlagsBitmask |= options::CLOption;
4765 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4768 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
4769 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);