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/Lanai.h"
30 #include "ToolChains/Linux.h"
31 #include "ToolChains/MSVC.h"
32 #include "ToolChains/MinGW.h"
33 #include "ToolChains/Minix.h"
34 #include "ToolChains/MipsLinux.h"
35 #include "ToolChains/Myriad.h"
36 #include "ToolChains/NaCl.h"
37 #include "ToolChains/NetBSD.h"
38 #include "ToolChains/OpenBSD.h"
39 #include "ToolChains/PS4CPU.h"
40 #include "ToolChains/Solaris.h"
41 #include "ToolChains/TCE.h"
42 #include "ToolChains/WebAssembly.h"
43 #include "ToolChains/XCore.h"
44 #include "clang/Basic/Version.h"
45 #include "clang/Basic/VirtualFileSystem.h"
46 #include "clang/Config/config.h"
47 #include "clang/Driver/Action.h"
48 #include "clang/Driver/Compilation.h"
49 #include "clang/Driver/DriverDiagnostic.h"
50 #include "clang/Driver/Job.h"
51 #include "clang/Driver/Options.h"
52 #include "clang/Driver/SanitizerArgs.h"
53 #include "clang/Driver/Tool.h"
54 #include "clang/Driver/ToolChain.h"
55 #include "llvm/ADT/ArrayRef.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/SmallSet.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/ADT/StringSet.h"
60 #include "llvm/ADT/StringSwitch.h"
61 #include "llvm/Config/llvm-config.h"
62 #include "llvm/Option/Arg.h"
63 #include "llvm/Option/ArgList.h"
64 #include "llvm/Option/OptSpecifier.h"
65 #include "llvm/Option/OptTable.h"
66 #include "llvm/Option/Option.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/FileSystem.h"
70 #include "llvm/Support/Path.h"
71 #include "llvm/Support/PrettyStackTrace.h"
72 #include "llvm/Support/Process.h"
73 #include "llvm/Support/Program.h"
74 #include "llvm/Support/StringSaver.h"
75 #include "llvm/Support/TargetRegistry.h"
76 #include "llvm/Support/raw_ostream.h"
81 #include <unistd.h> // getpid
84 using namespace clang::driver;
85 using namespace clang;
86 using namespace llvm::opt;
88 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
89 DiagnosticsEngine &Diags,
90 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
91 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
92 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
93 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
94 SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
95 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
96 CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
97 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
98 CCGenDiagnostics(false), TargetTriple(TargetTriple),
99 CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
100 CCCUsePCH(true), GenReproducer(false),
101 SuppressMissingInputWarning(false) {
103 // Provide a sane fallback if no VFS is specified.
105 this->VFS = vfs::getRealFileSystem();
107 Name = llvm::sys::path::filename(ClangExecutable);
108 Dir = llvm::sys::path::parent_path(ClangExecutable);
109 InstalledDir = Dir; // Provide a sensible default installed dir.
111 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
112 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
114 #if defined(CLANG_CONFIG_FILE_USER_DIR)
115 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
118 // Compute the path to the resource directory.
119 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
120 SmallString<128> P(Dir);
121 if (ClangResourceDir != "") {
122 llvm::sys::path::append(P, ClangResourceDir);
124 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
125 P = llvm::sys::path::parent_path(Dir);
126 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
127 CLANG_VERSION_STRING);
129 ResourceDir = P.str();
132 void Driver::ParseDriverMode(StringRef ProgramName,
133 ArrayRef<const char *> Args) {
134 if (ClangNameParts.isEmpty())
135 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
136 setDriverModeFromOption(ClangNameParts.DriverMode);
138 for (const char *ArgPtr : Args) {
139 // Ignore nullptrs, they are the response file's EOL markers.
140 if (ArgPtr == nullptr)
142 const StringRef Arg = ArgPtr;
143 setDriverModeFromOption(Arg);
147 void Driver::setDriverModeFromOption(StringRef Opt) {
148 const std::string OptName =
149 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
150 if (!Opt.startswith(OptName))
152 StringRef Value = Opt.drop_front(OptName.size());
154 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
155 .Case("gcc", GCCMode)
156 .Case("g++", GXXMode)
157 .Case("cpp", CPPMode)
162 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
165 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
166 bool &ContainsError) {
167 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
168 ContainsError = false;
170 unsigned IncludedFlagsBitmask;
171 unsigned ExcludedFlagsBitmask;
172 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
173 getIncludeExcludeOptionFlagMasks();
175 unsigned MissingArgIndex, MissingArgCount;
177 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
178 IncludedFlagsBitmask, ExcludedFlagsBitmask);
180 // Check for missing argument error.
181 if (MissingArgCount) {
182 Diag(diag::err_drv_missing_argument)
183 << Args.getArgString(MissingArgIndex) << MissingArgCount;
185 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
186 SourceLocation()) > DiagnosticsEngine::Warning;
189 // Check for unsupported options.
190 for (const Arg *A : Args) {
191 if (A->getOption().hasFlag(options::Unsupported)) {
193 auto ArgString = A->getAsString(Args);
195 if (getOpts().findNearest(
196 ArgString, Nearest, IncludedFlagsBitmask,
197 ExcludedFlagsBitmask | options::Unsupported) > 1) {
198 DiagID = diag::err_drv_unsupported_opt;
199 Diag(DiagID) << ArgString;
201 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
202 Diag(DiagID) << ArgString << Nearest;
204 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
205 DiagnosticsEngine::Warning;
209 // Warn about -mcpu= without an argument.
210 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
211 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
212 ContainsError |= Diags.getDiagnosticLevel(
213 diag::warn_drv_empty_joined_argument,
214 SourceLocation()) > DiagnosticsEngine::Warning;
218 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
220 auto ArgString = A->getAsString(Args);
222 if (getOpts().findNearest(
223 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
224 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
225 : diag::err_drv_unknown_argument;
226 Diags.Report(DiagID) << ArgString;
228 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
229 : diag::err_drv_unknown_argument_with_suggestion;
230 Diags.Report(DiagID) << ArgString << Nearest;
232 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
233 DiagnosticsEngine::Warning;
239 // Determine which compilation mode we are in. We look for options which
240 // affect the phase, starting with the earliest phases, and record which
241 // option we used to determine the final phase.
242 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
243 Arg **FinalPhaseArg) const {
244 Arg *PhaseArg = nullptr;
245 phases::ID FinalPhase;
247 // -{E,EP,P,M,MM} only run the preprocessor.
248 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
249 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
250 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
251 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
252 FinalPhase = phases::Preprocess;
254 // --precompile only runs up to precompilation.
255 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
256 FinalPhase = phases::Precompile;
258 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
259 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
260 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
261 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
262 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
263 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
264 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
265 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
266 options::OPT__analyze_auto)) ||
267 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
268 FinalPhase = phases::Compile;
270 // -S only runs up to the backend.
271 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
272 FinalPhase = phases::Backend;
274 // -c compilation only runs up to the assembler.
275 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
276 FinalPhase = phases::Assemble;
278 // Otherwise do everything.
280 FinalPhase = phases::Link;
283 *FinalPhaseArg = PhaseArg;
288 static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
289 StringRef Value, bool Claim = true) {
290 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
291 Args.getBaseArgs().MakeIndex(Value), Value.data());
292 Args.AddSynthesizedArg(A);
298 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
299 DerivedArgList *DAL = new DerivedArgList(Args);
301 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
302 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
303 for (Arg *A : Args) {
304 // Unfortunately, we have to parse some forwarding options (-Xassembler,
305 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
306 // (assembler and preprocessor), or bypass a previous driver ('collect2').
308 // Rewrite linker options, to replace --no-demangle with a custom internal
310 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
311 A->getOption().matches(options::OPT_Xlinker)) &&
312 A->containsValue("--no-demangle")) {
313 // Add the rewritten no-demangle argument.
314 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
316 // Add the remaining values as Xlinker arguments.
317 for (StringRef Val : A->getValues())
318 if (Val != "--no-demangle")
319 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
324 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
325 // some build systems. We don't try to be complete here because we don't
326 // care to encourage this usage model.
327 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
328 (A->getValue(0) == StringRef("-MD") ||
329 A->getValue(0) == StringRef("-MMD"))) {
330 // Rewrite to -MD/-MMD along with -MF.
331 if (A->getValue(0) == StringRef("-MD"))
332 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
334 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
335 if (A->getNumValues() == 2)
336 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
341 // Rewrite reserved library names.
342 if (A->getOption().matches(options::OPT_l)) {
343 StringRef Value = A->getValue();
345 // Rewrite unless -nostdlib is present.
346 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
347 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
351 // Rewrite unconditionally.
352 if (Value == "cc_kext") {
353 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
358 // Pick up inputs via the -- option.
359 if (A->getOption().matches(options::OPT__DASH_DASH)) {
361 for (StringRef Val : A->getValues())
362 DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
369 // Enforce -static if -miamcu is present.
370 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
371 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
373 // Add a default value of -mlinker-version=, if one was given and the user
374 // didn't specify one.
375 #if defined(HOST_LINK_VERSION)
376 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
377 strlen(HOST_LINK_VERSION) > 0) {
378 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
380 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
387 /// Compute target triple from args.
389 /// This routine provides the logic to compute a target triple from various
390 /// args passed to the driver and the default triple string.
391 static llvm::Triple computeTargetTriple(const Driver &D,
392 StringRef TargetTriple,
394 StringRef DarwinArchName = "") {
395 // FIXME: Already done in Compilation *Driver::BuildCompilation
396 if (const Arg *A = Args.getLastArg(options::OPT_target))
397 TargetTriple = A->getValue();
399 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
401 // Handle Apple-specific options available here.
402 if (Target.isOSBinFormatMachO()) {
403 // If an explicit Darwin arch name is given, that trumps all.
404 if (!DarwinArchName.empty()) {
405 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
409 // Handle the Darwin '-arch' flag.
410 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
411 StringRef ArchName = A->getValue();
412 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
416 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
417 // '-mbig-endian'/'-EB'.
418 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
419 options::OPT_mbig_endian)) {
420 if (A->getOption().matches(options::OPT_mlittle_endian)) {
421 llvm::Triple LE = Target.getLittleEndianArchVariant();
422 if (LE.getArch() != llvm::Triple::UnknownArch)
423 Target = std::move(LE);
425 llvm::Triple BE = Target.getBigEndianArchVariant();
426 if (BE.getArch() != llvm::Triple::UnknownArch)
427 Target = std::move(BE);
431 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
432 if (Target.getArch() == llvm::Triple::tce ||
433 Target.getOS() == llvm::Triple::Minix)
436 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
437 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
438 options::OPT_m32, options::OPT_m16);
440 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
442 if (A->getOption().matches(options::OPT_m64)) {
443 AT = Target.get64BitArchVariant().getArch();
444 if (Target.getEnvironment() == llvm::Triple::GNUX32)
445 Target.setEnvironment(llvm::Triple::GNU);
446 } else if (A->getOption().matches(options::OPT_mx32) &&
447 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
448 AT = llvm::Triple::x86_64;
449 Target.setEnvironment(llvm::Triple::GNUX32);
450 } else if (A->getOption().matches(options::OPT_m32)) {
451 AT = Target.get32BitArchVariant().getArch();
452 if (Target.getEnvironment() == llvm::Triple::GNUX32)
453 Target.setEnvironment(llvm::Triple::GNU);
454 } else if (A->getOption().matches(options::OPT_m16) &&
455 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
456 AT = llvm::Triple::x86;
457 Target.setEnvironment(llvm::Triple::CODE16);
460 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
464 // Handle -miamcu flag.
465 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
466 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
467 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
470 if (A && !A->getOption().matches(options::OPT_m32))
471 D.Diag(diag::err_drv_argument_not_allowed_with)
472 << "-miamcu" << A->getBaseArg().getAsString(Args);
474 Target.setArch(llvm::Triple::x86);
475 Target.setArchName("i586");
476 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
477 Target.setEnvironmentName("");
478 Target.setOS(llvm::Triple::ELFIAMCU);
479 Target.setVendor(llvm::Triple::UnknownVendor);
480 Target.setVendorName("intel");
486 // Parse the LTO options and record the type of LTO compilation
487 // based on which -f(no-)?lto(=.*)? option occurs last.
488 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
490 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
491 options::OPT_fno_lto, false))
494 StringRef LTOName("full");
496 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
498 LTOName = A->getValue();
500 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
501 .Case("full", LTOK_Full)
502 .Case("thin", LTOK_Thin)
503 .Default(LTOK_Unknown);
505 if (LTOMode == LTOK_Unknown) {
507 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
512 /// Compute the desired OpenMP runtime from the flags provided.
513 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
514 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
516 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
518 RuntimeName = A->getValue();
520 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
521 .Case("libomp", OMPRT_OMP)
522 .Case("libgomp", OMPRT_GOMP)
523 .Case("libiomp5", OMPRT_IOMP5)
524 .Default(OMPRT_Unknown);
526 if (RT == OMPRT_Unknown) {
528 Diag(diag::err_drv_unsupported_option_argument)
529 << A->getOption().getName() << A->getValue();
531 // FIXME: We could use a nicer diagnostic here.
532 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
538 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
544 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
545 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
547 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
548 return types::isCuda(I.first);
552 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
553 return types::isHIP(I.first);
555 C.getInputArgs().hasArg(options::OPT_hip_link);
556 if (IsCuda && IsHIP) {
557 Diag(clang::diag::err_drv_mix_cuda_hip);
561 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
562 const llvm::Triple &HostTriple = HostTC->getTriple();
563 StringRef DeviceTripleStr;
564 auto OFK = Action::OFK_Cuda;
566 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
567 llvm::Triple CudaTriple(DeviceTripleStr);
568 // Use the CUDA and host triples as the key into the ToolChains map,
569 // because the device toolchain we create depends on both.
570 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
572 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
573 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
575 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
577 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
578 const llvm::Triple &HostTriple = HostTC->getTriple();
579 StringRef DeviceTripleStr;
580 auto OFK = Action::OFK_HIP;
581 DeviceTripleStr = "amdgcn-amd-amdhsa";
582 llvm::Triple HIPTriple(DeviceTripleStr);
583 // Use the HIP and host triples as the key into the ToolChains map,
584 // because the device toolchain we create depends on both.
585 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
587 HIPTC = llvm::make_unique<toolchains::HIPToolChain>(
588 *this, HIPTriple, *HostTC, C.getInputArgs());
590 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
596 // We need to generate an OpenMP toolchain if the user specified targets with
597 // the -fopenmp-targets option.
598 if (Arg *OpenMPTargets =
599 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
600 if (OpenMPTargets->getNumValues()) {
601 // We expect that -fopenmp-targets is always used in conjunction with the
602 // option -fopenmp specifying a valid runtime with offloading support,
603 // i.e. libomp or libiomp.
604 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
605 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
606 options::OPT_fno_openmp, false);
607 if (HasValidOpenMPRuntime) {
608 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
609 HasValidOpenMPRuntime =
610 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
613 if (HasValidOpenMPRuntime) {
614 llvm::StringMap<const char *> FoundNormalizedTriples;
615 for (const char *Val : OpenMPTargets->getValues()) {
616 llvm::Triple TT(Val);
617 std::string NormalizedName = TT.normalize();
619 // Make sure we don't have a duplicate triple.
620 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
621 if (Duplicate != FoundNormalizedTriples.end()) {
622 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
623 << Val << Duplicate->second;
627 // Store the current triple so that we can check for duplicates in the
628 // following iterations.
629 FoundNormalizedTriples[NormalizedName] = Val;
631 // If the specified target is invalid, emit a diagnostic.
632 if (TT.getArch() == llvm::Triple::UnknownArch)
633 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
636 // CUDA toolchains have to be selected differently. They pair host
637 // and device in their implementation.
639 const ToolChain *HostTC =
640 C.getSingleOffloadToolChain<Action::OFK_Host>();
641 assert(HostTC && "Host toolchain should be always defined.");
643 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
645 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
646 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
649 TC = &getToolChain(C.getInputArgs(), TT);
650 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
654 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
656 Diag(clang::diag::warn_drv_empty_joined_argument)
657 << OpenMPTargets->getAsString(C.getInputArgs());
661 // TODO: Add support for other offloading programming models here.
665 /// Looks the given directories for the specified file.
667 /// \param[out] FilePath File path, if the file was found.
668 /// \param[in] Dirs Directories used for the search.
669 /// \param[in] FileName Name of the file to search for.
670 /// \return True if file was found.
672 /// Looks for file specified by FileName sequentially in directories specified
675 static bool searchForFile(SmallVectorImpl<char> &FilePath,
676 ArrayRef<std::string> Dirs,
677 StringRef FileName) {
678 SmallString<128> WPath;
679 for (const StringRef &Dir : Dirs) {
683 llvm::sys::path::append(WPath, Dir, FileName);
684 llvm::sys::path::native(WPath);
685 if (llvm::sys::fs::is_regular_file(WPath)) {
686 FilePath = std::move(WPath);
693 bool Driver::readConfigFile(StringRef FileName) {
694 // Try reading the given file.
695 SmallVector<const char *, 32> NewCfgArgs;
696 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
697 Diag(diag::err_drv_cannot_read_config_file) << FileName;
701 // Read options from config file.
702 llvm::SmallString<128> CfgFileName(FileName);
703 llvm::sys::path::native(CfgFileName);
704 ConfigFile = CfgFileName.str();
706 CfgOptions = llvm::make_unique<InputArgList>(
707 ParseArgStrings(NewCfgArgs, ContainErrors));
713 if (CfgOptions->hasArg(options::OPT_config)) {
715 Diag(diag::err_drv_nested_config_file);
719 // Claim all arguments that come from a configuration file so that the driver
720 // does not warn on any that is unused.
721 for (Arg *A : *CfgOptions)
726 bool Driver::loadConfigFile() {
727 std::string CfgFileName;
728 bool FileSpecifiedExplicitly = false;
730 // Process options that change search path for config files.
732 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
733 SmallString<128> CfgDir;
735 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
736 if (!CfgDir.empty()) {
737 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
738 SystemConfigDir.clear();
740 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
743 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
744 SmallString<128> CfgDir;
746 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
747 if (!CfgDir.empty()) {
748 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
749 UserConfigDir.clear();
751 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
756 // First try to find config file specified in command line.
758 std::vector<std::string> ConfigFiles =
759 CLOptions->getAllArgValues(options::OPT_config);
760 if (ConfigFiles.size() > 1) {
761 Diag(diag::err_drv_duplicate_config);
765 if (!ConfigFiles.empty()) {
766 CfgFileName = ConfigFiles.front();
767 assert(!CfgFileName.empty());
769 // If argument contains directory separator, treat it as a path to
770 // configuration file.
771 if (llvm::sys::path::has_parent_path(CfgFileName)) {
772 SmallString<128> CfgFilePath;
773 if (llvm::sys::path::is_relative(CfgFileName))
774 llvm::sys::fs::current_path(CfgFilePath);
775 llvm::sys::path::append(CfgFilePath, CfgFileName);
776 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
777 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
780 return readConfigFile(CfgFilePath);
783 FileSpecifiedExplicitly = true;
787 // If config file is not specified explicitly, try to deduce configuration
788 // from executable name. For instance, an executable 'armv7l-clang' will
789 // search for config file 'armv7l-clang.cfg'.
790 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
791 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
793 if (CfgFileName.empty())
796 // Determine architecture part of the file name, if it is present.
797 StringRef CfgFileArch = CfgFileName;
798 size_t ArchPrefixLen = CfgFileArch.find('-');
799 if (ArchPrefixLen == StringRef::npos)
800 ArchPrefixLen = CfgFileArch.size();
801 llvm::Triple CfgTriple;
802 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
803 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
804 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
807 if (!StringRef(CfgFileName).endswith(".cfg"))
808 CfgFileName += ".cfg";
810 // If config file starts with architecture name and command line options
811 // redefine architecture (with options like -m32 -LE etc), try finding new
812 // config file with that architecture.
813 SmallString<128> FixedConfigFile;
814 size_t FixedArchPrefixLen = 0;
816 // Get architecture name from config file name like 'i386.cfg' or
817 // 'armv7l-clang.cfg'.
818 // Check if command line options changes effective triple.
819 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
820 CfgTriple.getTriple(), *CLOptions);
821 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
822 FixedConfigFile = EffectiveTriple.getArchName();
823 FixedArchPrefixLen = FixedConfigFile.size();
824 // Append the rest of original file name so that file name transforms
825 // like: i386-clang.cfg -> x86_64-clang.cfg.
826 if (ArchPrefixLen < CfgFileName.size())
827 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
831 // Prepare list of directories where config file is searched for.
832 SmallVector<std::string, 3> CfgFileSearchDirs;
833 CfgFileSearchDirs.push_back(UserConfigDir);
834 CfgFileSearchDirs.push_back(SystemConfigDir);
835 CfgFileSearchDirs.push_back(Dir);
837 // Try to find config file. First try file with corrected architecture.
838 llvm::SmallString<128> CfgFilePath;
839 if (!FixedConfigFile.empty()) {
840 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
841 return readConfigFile(CfgFilePath);
842 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
843 FixedConfigFile.resize(FixedArchPrefixLen);
844 FixedConfigFile.append(".cfg");
845 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
846 return readConfigFile(CfgFilePath);
849 // Then try original file name.
850 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
851 return readConfigFile(CfgFilePath);
853 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
854 if (!ClangNameParts.ModeSuffix.empty() &&
855 !ClangNameParts.TargetPrefix.empty()) {
856 CfgFileName.assign(ClangNameParts.TargetPrefix);
857 CfgFileName.append(".cfg");
858 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
859 return readConfigFile(CfgFilePath);
862 // Report error but only if config file was specified explicitly, by option
863 // --config. If it was deduced from executable name, it is not an error.
864 if (FileSpecifiedExplicitly) {
865 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
866 for (const std::string &SearchDir : CfgFileSearchDirs)
867 if (!SearchDir.empty())
868 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
875 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
876 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
878 // FIXME: Handle environment options which affect driver behavior, somewhere
879 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
881 if (Optional<std::string> CompilerPathValue =
882 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
883 StringRef CompilerPath = *CompilerPathValue;
884 while (!CompilerPath.empty()) {
885 std::pair<StringRef, StringRef> Split =
886 CompilerPath.split(llvm::sys::EnvPathSeparator);
887 PrefixDirs.push_back(Split.first);
888 CompilerPath = Split.second;
892 // We look for the driver mode option early, because the mode can affect
893 // how other options are parsed.
894 ParseDriverMode(ClangExecutable, ArgList.slice(1));
896 // FIXME: What are we going to do with -V and -b?
898 // Arguments specified in command line.
900 CLOptions = llvm::make_unique<InputArgList>(
901 ParseArgStrings(ArgList.slice(1), ContainsError));
903 // Try parsing configuration file.
905 ContainsError = loadConfigFile();
906 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
908 // All arguments, from both config file and command line.
909 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
910 : std::move(*CLOptions));
912 for (auto *Opt : *CLOptions) {
913 if (Opt->getOption().matches(options::OPT_config))
915 unsigned Index = Args.MakeIndex(Opt->getSpelling());
916 const Arg *BaseArg = &Opt->getBaseArg();
919 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
921 Copy->getValues() = Opt->getValues();
922 if (Opt->isClaimed())
927 // FIXME: This stuff needs to go into the Compilation, not the driver.
930 // Silence driver warnings if requested
931 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
933 // -no-canonical-prefixes is used very early in main.
934 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
937 Args.ClaimAllArgs(options::OPT_pipe);
939 // Extract -ccc args.
941 // FIXME: We need to figure out where this behavior should live. Most of it
942 // should be outside in the client; the parts that aren't should have proper
943 // options, either by introducing new ones or by overloading gcc ones like -V
945 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
946 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
947 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
948 CCCGenericGCCName = A->getValue();
950 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
951 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
952 options::OPT_fno_crash_diagnostics,
953 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
954 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
955 // and getToolChain is const.
957 // clang-cl targets MSVC-style Win32.
958 llvm::Triple T(TargetTriple);
959 T.setOS(llvm::Triple::Win32);
960 T.setVendor(llvm::Triple::PC);
961 T.setEnvironment(llvm::Triple::MSVC);
962 T.setObjectFormat(llvm::Triple::COFF);
963 TargetTriple = T.str();
965 if (const Arg *A = Args.getLastArg(options::OPT_target))
966 TargetTriple = A->getValue();
967 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
968 Dir = InstalledDir = A->getValue();
969 for (const Arg *A : Args.filtered(options::OPT_B)) {
971 PrefixDirs.push_back(A->getValue(0));
973 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
974 SysRoot = A->getValue();
975 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
976 DyldPrefix = A->getValue();
978 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
979 ResourceDir = A->getValue();
981 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
982 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
983 .Case("cwd", SaveTempsCwd)
984 .Case("obj", SaveTempsObj)
985 .Default(SaveTempsCwd);
990 // Process -fembed-bitcode= flags.
991 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
992 StringRef Name = A->getValue();
993 unsigned Model = llvm::StringSwitch<unsigned>(Name)
994 .Case("off", EmbedNone)
995 .Case("all", EmbedBitcode)
996 .Case("bitcode", EmbedBitcode)
997 .Case("marker", EmbedMarker)
1000 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1003 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1006 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1007 llvm::make_unique<InputArgList>(std::move(Args));
1009 // Perform the default argument translations.
1010 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1012 // Owned by the host.
1013 const ToolChain &TC = getToolChain(
1014 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1016 // The compilation takes ownership of Args.
1017 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1020 if (!HandleImmediateArgs(*C))
1023 // Construct the list of inputs.
1025 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1027 // Populate the tool chains for the offloading devices, if any.
1028 CreateOffloadingDeviceToolChains(*C, Inputs);
1030 // Construct the list of abstract actions to perform for this compilation. On
1031 // MachO targets this uses the driver-driver and universal actions.
1032 if (TC.getTriple().isOSBinFormatMachO())
1033 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1035 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1037 if (CCCPrintPhases) {
1047 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1048 llvm::opt::ArgStringList ASL;
1049 for (const auto *A : Args)
1050 A->render(Args, ASL);
1052 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1053 if (I != ASL.begin())
1055 Command::printArg(OS, *I, true);
1060 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1061 SmallString<128> &CrashDiagDir) {
1062 using namespace llvm::sys;
1063 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1064 "Only knows about .crash files on Darwin");
1066 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1067 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1068 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1069 path::home_directory(CrashDiagDir);
1070 if (CrashDiagDir.startswith("/var/root"))
1072 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1080 fs::file_status FileStatus;
1081 TimePoint<> LastAccessTime;
1082 SmallString<128> CrashFilePath;
1083 // Lookup the .crash files and get the one generated by a subprocess spawned
1084 // by this driver invocation.
1085 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1086 File != FileEnd && !EC; File.increment(EC)) {
1087 StringRef FileName = path::filename(File->path());
1088 if (!FileName.startswith(Name))
1090 if (fs::status(File->path(), FileStatus))
1092 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1093 llvm::MemoryBuffer::getFile(File->path());
1096 // The first line should start with "Process:", otherwise this isn't a real
1098 StringRef Data = CrashFile.get()->getBuffer();
1099 if (!Data.startswith("Process:"))
1101 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1102 size_t ParentProcPos = Data.find("Parent Process:");
1103 if (ParentProcPos == StringRef::npos)
1105 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1106 if (LineEnd == StringRef::npos)
1108 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1109 int OpenBracket = -1, CloseBracket = -1;
1110 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1111 if (ParentProcess[i] == '[')
1113 if (ParentProcess[i] == ']')
1116 // Extract the parent process PID from the .crash file and check whether
1117 // it matches this driver invocation pid.
1119 if (OpenBracket < 0 || CloseBracket < 0 ||
1120 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1121 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1125 // Found a .crash file matching the driver pid. To avoid getting an older
1126 // and misleading crash file, continue looking for the most recent.
1127 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1128 // multiple crashes poiting to the same parent process. Since the driver
1129 // does not collect pid information for the dispatched invocation there's
1130 // currently no way to distinguish among them.
1131 const auto FileAccessTime = FileStatus.getLastModificationTime();
1132 if (FileAccessTime > LastAccessTime) {
1133 CrashFilePath.assign(File->path());
1134 LastAccessTime = FileAccessTime;
1138 // If found, copy it over to the location of other reproducer files.
1139 if (!CrashFilePath.empty()) {
1140 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1149 // When clang crashes, produce diagnostic information including the fully
1150 // preprocessed source file(s). Request that the developer attach the
1151 // diagnostic information to a bug report.
1152 void Driver::generateCompilationDiagnostics(
1153 Compilation &C, const Command &FailingCommand,
1154 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1155 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1158 // Don't try to generate diagnostics for link or dsymutil jobs.
1159 if (FailingCommand.getCreator().isLinkJob() ||
1160 FailingCommand.getCreator().isDsymutilJob())
1163 // Print the version of the compiler.
1164 PrintVersion(C, llvm::errs());
1166 Diag(clang::diag::note_drv_command_failed_diag_msg)
1167 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1168 "crash backtrace, preprocessed source, and associated run script.";
1170 // Suppress driver output and emit preprocessor output to temp file.
1172 CCGenDiagnostics = true;
1174 // Save the original job command(s).
1175 Command Cmd = FailingCommand;
1177 // Keep track of whether we produce any errors while trying to produce
1178 // preprocessed sources.
1179 DiagnosticErrorTrap Trap(Diags);
1181 // Suppress tool output.
1182 C.initCompilationForDiagnostics();
1184 // Construct the list of inputs.
1186 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1188 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1189 bool IgnoreInput = false;
1191 // Ignore input from stdin or any inputs that cannot be preprocessed.
1192 // Check type first as not all linker inputs have a value.
1193 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1195 } else if (!strcmp(it->second->getValue(), "-")) {
1196 Diag(clang::diag::note_drv_command_failed_diag_msg)
1197 << "Error generating preprocessed source(s) - "
1198 "ignoring input from stdin.";
1203 it = Inputs.erase(it);
1210 if (Inputs.empty()) {
1211 Diag(clang::diag::note_drv_command_failed_diag_msg)
1212 << "Error generating preprocessed source(s) - "
1213 "no preprocessable inputs.";
1217 // Don't attempt to generate preprocessed files if multiple -arch options are
1218 // used, unless they're all duplicates.
1219 llvm::StringSet<> ArchNames;
1220 for (const Arg *A : C.getArgs()) {
1221 if (A->getOption().matches(options::OPT_arch)) {
1222 StringRef ArchName = A->getValue();
1223 ArchNames.insert(ArchName);
1226 if (ArchNames.size() > 1) {
1227 Diag(clang::diag::note_drv_command_failed_diag_msg)
1228 << "Error generating preprocessed source(s) - cannot generate "
1229 "preprocessed source with multiple -arch options.";
1233 // Construct the list of abstract actions to perform for this compilation. On
1234 // Darwin OSes this uses the driver-driver and builds universal actions.
1235 const ToolChain &TC = C.getDefaultToolChain();
1236 if (TC.getTriple().isOSBinFormatMachO())
1237 BuildUniversalActions(C, TC, Inputs);
1239 BuildActions(C, C.getArgs(), Inputs, C.getActions());
1243 // If there were errors building the compilation, quit now.
1244 if (Trap.hasErrorOccurred()) {
1245 Diag(clang::diag::note_drv_command_failed_diag_msg)
1246 << "Error generating preprocessed source(s).";
1250 // Generate preprocessed output.
1251 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1252 C.ExecuteJobs(C.getJobs(), FailingCommands);
1254 // If any of the preprocessing commands failed, clean up and exit.
1255 if (!FailingCommands.empty()) {
1256 Diag(clang::diag::note_drv_command_failed_diag_msg)
1257 << "Error generating preprocessed source(s).";
1261 const ArgStringList &TempFiles = C.getTempFiles();
1262 if (TempFiles.empty()) {
1263 Diag(clang::diag::note_drv_command_failed_diag_msg)
1264 << "Error generating preprocessed source(s).";
1268 Diag(clang::diag::note_drv_command_failed_diag_msg)
1269 << "\n********************\n\n"
1270 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1271 "Preprocessed source(s) and associated run script(s) are located at:";
1273 SmallString<128> VFS;
1274 SmallString<128> ReproCrashFilename;
1275 for (const char *TempFile : TempFiles) {
1276 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1278 Report->TemporaryFiles.push_back(TempFile);
1279 if (ReproCrashFilename.empty()) {
1280 ReproCrashFilename = TempFile;
1281 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1283 if (StringRef(TempFile).endswith(".cache")) {
1284 // In some cases (modules) we'll dump extra data to help with reproducing
1285 // the crash into a directory next to the output.
1286 VFS = llvm::sys::path::filename(TempFile);
1287 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1291 // Assume associated files are based off of the first temporary file.
1292 CrashReportInfo CrashInfo(TempFiles[0], VFS);
1294 llvm::SmallString<128> Script(CrashInfo.Filename);
1295 llvm::sys::path::replace_extension(Script, "sh");
1297 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
1299 Diag(clang::diag::note_drv_command_failed_diag_msg)
1300 << "Error generating run script: " << Script << " " << EC.message();
1302 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1303 << "# Driver args: ";
1304 printArgList(ScriptOS, C.getInputArgs());
1305 ScriptOS << "# Original command: ";
1306 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1307 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1308 if (!AdditionalInformation.empty())
1309 ScriptOS << "\n# Additional information: " << AdditionalInformation
1312 Report->TemporaryFiles.push_back(Script.str());
1313 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1316 // On darwin, provide information about the .crash diagnostic report.
1317 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1318 SmallString<128> CrashDiagDir;
1319 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1320 Diag(clang::diag::note_drv_command_failed_diag_msg)
1321 << ReproCrashFilename.str();
1322 } else { // Suggest a directory for the user to look for .crash files.
1323 llvm::sys::path::append(CrashDiagDir, Name);
1324 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1325 Diag(clang::diag::note_drv_command_failed_diag_msg)
1326 << "Crash backtrace is located in";
1327 Diag(clang::diag::note_drv_command_failed_diag_msg)
1328 << CrashDiagDir.str();
1329 Diag(clang::diag::note_drv_command_failed_diag_msg)
1330 << "(choose the .crash file that corresponds to your crash)";
1334 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1335 options::OPT_frewrite_map_file_EQ))
1336 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1338 Diag(clang::diag::note_drv_command_failed_diag_msg)
1339 << "\n\n********************";
1342 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1343 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
1344 // if the tool does not support response files, there is a chance/ that things
1345 // will just work without a response file, so we silently just skip it.
1346 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1347 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
1350 std::string TmpName = GetTemporaryPath("response", "txt");
1351 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1354 int Driver::ExecuteCompilation(
1356 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1357 // Just print if -### was present.
1358 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1359 C.getJobs().Print(llvm::errs(), "\n", true);
1363 // If there were errors building the compilation, quit now.
1364 if (Diags.hasErrorOccurred())
1367 // Set up response file names for each command, if necessary
1368 for (auto &Job : C.getJobs())
1369 setUpResponseFiles(C, Job);
1371 C.ExecuteJobs(C.getJobs(), FailingCommands);
1373 // If the command succeeded, we are done.
1374 if (FailingCommands.empty())
1377 // Otherwise, remove result files and print extra information about abnormal
1379 for (const auto &CmdPair : FailingCommands) {
1380 int Res = CmdPair.first;
1381 const Command *FailingCommand = CmdPair.second;
1383 // Remove result files if we're not saving temps.
1384 if (!isSaveTempsEnabled()) {
1385 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1386 C.CleanupFileMap(C.getResultFiles(), JA, true);
1388 // Failure result files are valid unless we crashed.
1390 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1393 // Print extra information about abnormal failures, if possible.
1395 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1396 // status was 1, assume the command failed normally. In particular, if it
1397 // was the compiler then assume it gave a reasonable error code. Failures
1398 // in other tools are less common, and they generally have worse
1399 // diagnostics, so always print the diagnostic there.
1400 const Tool &FailingTool = FailingCommand->getCreator();
1402 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1403 // FIXME: See FIXME above regarding result code interpretation.
1405 Diag(clang::diag::err_drv_command_signalled)
1406 << FailingTool.getShortName();
1408 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1415 void Driver::PrintHelp(bool ShowHidden) const {
1416 unsigned IncludedFlagsBitmask;
1417 unsigned ExcludedFlagsBitmask;
1418 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1419 getIncludeExcludeOptionFlagMasks();
1421 ExcludedFlagsBitmask |= options::NoDriverOption;
1423 ExcludedFlagsBitmask |= HelpHidden;
1425 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1426 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1427 /*ShowAllAliases=*/false);
1430 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1431 // FIXME: The following handlers should use a callback mechanism, we don't
1432 // know what the client would like to do.
1433 OS << getClangFullVersion() << '\n';
1434 const ToolChain &TC = C.getDefaultToolChain();
1435 OS << "Target: " << TC.getTripleString() << '\n';
1437 // Print the threading model.
1438 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1439 // Don't print if the ToolChain would have barfed on it already
1440 if (TC.isThreadModelSupported(A->getValue()))
1441 OS << "Thread model: " << A->getValue();
1443 OS << "Thread model: " << TC.getThreadModel();
1446 // Print out the install directory.
1447 OS << "InstalledDir: " << InstalledDir << '\n';
1449 // If configuration file was used, print its path.
1450 if (!ConfigFile.empty())
1451 OS << "Configuration file: " << ConfigFile << '\n';
1454 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1456 static void PrintDiagnosticCategories(raw_ostream &OS) {
1457 // Skip the empty category.
1458 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1460 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1463 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1464 if (PassedFlags == "")
1466 // Print out all options that start with a given argument. This is used for
1467 // shell autocompletion.
1468 std::vector<std::string> SuggestedCompletions;
1469 std::vector<std::string> Flags;
1471 unsigned short DisableFlags =
1472 options::NoDriverOption | options::Unsupported | options::Ignored;
1474 // Parse PassedFlags by "," as all the command-line flags are passed to this
1475 // function separated by ","
1476 StringRef TargetFlags = PassedFlags;
1477 while (TargetFlags != "") {
1479 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1480 Flags.push_back(std::string(CurFlag));
1483 // We want to show cc1-only options only when clang is invoked with -cc1 or
1485 if (std::find(Flags.begin(), Flags.end(), "-Xclang") != Flags.end() ||
1486 std::find(Flags.begin(), Flags.end(), "-cc1") != Flags.end())
1487 DisableFlags &= ~options::NoDriverOption;
1490 Cur = Flags.at(Flags.size() - 1);
1492 if (Flags.size() >= 2) {
1493 Prev = Flags.at(Flags.size() - 2);
1494 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1497 if (SuggestedCompletions.empty())
1498 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1500 if (SuggestedCompletions.empty()) {
1501 // If the flag is in the form of "--autocomplete=-foo",
1502 // we were requested to print out all option names that start with "-foo".
1503 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1504 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
1506 // We have to query the -W flags manually as they're not in the OptTable.
1507 // TODO: Find a good way to add them to OptTable instead and them remove
1509 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1510 if (S.startswith(Cur))
1511 SuggestedCompletions.push_back(S);
1514 // Sort the autocomplete candidates so that shells print them out in a
1515 // deterministic order. We could sort in any way, but we chose
1516 // case-insensitive sorting for consistency with the -help option
1517 // which prints out options in the case-insensitive alphabetical order.
1518 llvm::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
1519 [](StringRef A, StringRef B) {
1520 if (int X = A.compare_lower(B))
1522 return A.compare(B) > 0;
1525 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1528 bool Driver::HandleImmediateArgs(const Compilation &C) {
1529 // The order these options are handled in gcc is all over the place, but we
1530 // don't expect inconsistencies w.r.t. that to matter in practice.
1532 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1533 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1537 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1538 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1539 // return an answer which matches our definition of __VERSION__.
1541 // If we want to return a more correct answer some day, then we should
1542 // introduce a non-pedantically GCC compatible mode to Clang in which we
1543 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1544 llvm::outs() << "4.2.1\n";
1548 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1549 PrintDiagnosticCategories(llvm::outs());
1553 if (C.getArgs().hasArg(options::OPT_help) ||
1554 C.getArgs().hasArg(options::OPT__help_hidden)) {
1555 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1559 if (C.getArgs().hasArg(options::OPT__version)) {
1560 // Follow gcc behavior and use stdout for --version and stderr for -v.
1561 PrintVersion(C, llvm::outs());
1565 if (C.getArgs().hasArg(options::OPT_v) ||
1566 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1567 PrintVersion(C, llvm::errs());
1568 SuppressMissingInputWarning = true;
1571 if (C.getArgs().hasArg(options::OPT_v)) {
1572 if (!SystemConfigDir.empty())
1573 llvm::errs() << "System configuration file directory: "
1574 << SystemConfigDir << "\n";
1575 if (!UserConfigDir.empty())
1576 llvm::errs() << "User configuration file directory: "
1577 << UserConfigDir << "\n";
1580 const ToolChain &TC = C.getDefaultToolChain();
1582 if (C.getArgs().hasArg(options::OPT_v))
1583 TC.printVerboseInfo(llvm::errs());
1585 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1586 llvm::outs() << ResourceDir << '\n';
1590 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1591 llvm::outs() << "programs: =";
1592 bool separator = false;
1593 for (const std::string &Path : TC.getProgramPaths()) {
1595 llvm::outs() << ':';
1596 llvm::outs() << Path;
1599 llvm::outs() << "\n";
1600 llvm::outs() << "libraries: =" << ResourceDir;
1602 StringRef sysroot = C.getSysRoot();
1604 for (const std::string &Path : TC.getFilePaths()) {
1605 // Always print a separator. ResourceDir was the first item shown.
1606 llvm::outs() << ':';
1607 // Interpretation of leading '=' is needed only for NetBSD.
1609 llvm::outs() << sysroot << Path.substr(1);
1611 llvm::outs() << Path;
1613 llvm::outs() << "\n";
1617 // FIXME: The following handlers should use a callback mechanism, we don't
1618 // know what the client would like to do.
1619 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1620 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1624 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1625 StringRef ProgName = A->getValue();
1627 // Null program name cannot have a path.
1628 if (! ProgName.empty())
1629 llvm::outs() << GetProgramPath(ProgName, TC);
1631 llvm::outs() << "\n";
1635 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1636 StringRef PassedFlags = A->getValue();
1637 HandleAutocompletions(PassedFlags);
1641 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1642 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1643 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1644 RegisterEffectiveTriple TripleRAII(TC, Triple);
1646 case ToolChain::RLT_CompilerRT:
1647 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1649 case ToolChain::RLT_Libgcc:
1650 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1656 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1657 for (const Multilib &Multilib : TC.getMultilibs())
1658 llvm::outs() << Multilib << "\n";
1662 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1663 for (const Multilib &Multilib : TC.getMultilibs()) {
1664 if (Multilib.gccSuffix().empty())
1665 llvm::outs() << ".\n";
1667 StringRef Suffix(Multilib.gccSuffix());
1668 assert(Suffix.front() == '/');
1669 llvm::outs() << Suffix.substr(1) << "\n";
1677 // Display an action graph human-readably. Action A is the "sink" node
1678 // and latest-occuring action. Traversal is in pre-order, visiting the
1679 // inputs to each action before printing the action itself.
1680 static unsigned PrintActions1(const Compilation &C, Action *A,
1681 std::map<Action *, unsigned> &Ids) {
1682 if (Ids.count(A)) // A was already visited.
1686 llvm::raw_string_ostream os(str);
1688 os << Action::getClassName(A->getKind()) << ", ";
1689 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1690 os << "\"" << IA->getInputArg().getValue() << "\"";
1691 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1692 os << '"' << BIA->getArchName() << '"' << ", {"
1693 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1694 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1695 bool IsFirst = true;
1696 OA->doOnEachDependence(
1697 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1698 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1699 // sm_35 this will generate:
1700 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1701 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1706 os << A->getOffloadingKindPrefix();
1710 os << TC->getTriple().normalize();
1713 os << ":" << BoundArch;
1716 os << " {" << PrintActions1(C, A, Ids) << "}";
1720 const ActionList *AL = &A->getInputs();
1723 const char *Prefix = "{";
1724 for (Action *PreRequisite : *AL) {
1725 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1733 // Append offload info for all options other than the offloading action
1734 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1735 std::string offload_str;
1736 llvm::raw_string_ostream offload_os(offload_str);
1737 if (!isa<OffloadAction>(A)) {
1738 auto S = A->getOffloadingKindPrefix();
1740 offload_os << ", (" << S;
1741 if (A->getOffloadingArch())
1742 offload_os << ", " << A->getOffloadingArch();
1747 unsigned Id = Ids.size();
1749 llvm::errs() << Id << ": " << os.str() << ", "
1750 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1755 // Print the action graphs in a compilation C.
1756 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1757 void Driver::PrintActions(const Compilation &C) const {
1758 std::map<Action *, unsigned> Ids;
1759 for (Action *A : C.getActions())
1760 PrintActions1(C, A, Ids);
1763 /// Check whether the given input tree contains any compilation or
1764 /// assembly actions.
1765 static bool ContainsCompileOrAssembleAction(const Action *A) {
1766 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1767 isa<AssembleJobAction>(A))
1770 for (const Action *Input : A->inputs())
1771 if (ContainsCompileOrAssembleAction(Input))
1777 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1778 const InputList &BAInputs) const {
1779 DerivedArgList &Args = C.getArgs();
1780 ActionList &Actions = C.getActions();
1781 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1782 // Collect the list of architectures. Duplicates are allowed, but should only
1783 // be handled once (in the order seen).
1784 llvm::StringSet<> ArchNames;
1785 SmallVector<const char *, 4> Archs;
1786 for (Arg *A : Args) {
1787 if (A->getOption().matches(options::OPT_arch)) {
1788 // Validate the option here; we don't save the type here because its
1789 // particular spelling may participate in other driver choices.
1790 llvm::Triple::ArchType Arch =
1791 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1792 if (Arch == llvm::Triple::UnknownArch) {
1793 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1798 if (ArchNames.insert(A->getValue()).second)
1799 Archs.push_back(A->getValue());
1803 // When there is no explicit arch for this platform, make sure we still bind
1804 // the architecture (to the default) so that -Xarch_ is handled correctly.
1806 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1808 ActionList SingleActions;
1809 BuildActions(C, Args, BAInputs, SingleActions);
1811 // Add in arch bindings for every top level action, as well as lipo and
1812 // dsymutil steps if needed.
1813 for (Action* Act : SingleActions) {
1814 // Make sure we can lipo this kind of output. If not (and it is an actual
1815 // output) then we disallow, since we can't create an output file with the
1816 // right name without overwriting it. We could remove this oddity by just
1817 // changing the output names to include the arch, which would also fix
1818 // -save-temps. Compatibility wins for now.
1820 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1821 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1822 << types::getTypeName(Act->getType());
1825 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1826 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1828 // Lipo if necessary, we do it this way because we need to set the arch flag
1829 // so that -Xarch_ gets overwritten.
1830 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1831 Actions.append(Inputs.begin(), Inputs.end());
1833 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1835 // Handle debug info queries.
1836 Arg *A = Args.getLastArg(options::OPT_g_Group);
1837 if (A && !A->getOption().matches(options::OPT_g0) &&
1838 !A->getOption().matches(options::OPT_gstabs) &&
1839 ContainsCompileOrAssembleAction(Actions.back())) {
1841 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1842 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1843 // because the debug info will refer to a temporary object file which
1844 // will be removed at the end of the compilation process.
1845 if (Act->getType() == types::TY_Image) {
1847 Inputs.push_back(Actions.back());
1850 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1853 // Verify the debug info output.
1854 if (Args.hasArg(options::OPT_verify_debug_info)) {
1855 Action* LastAction = Actions.back();
1857 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1858 LastAction, types::TY_Nothing));
1864 /// Check that the file referenced by Value exists. If it doesn't,
1865 /// issue a diagnostic and return false.
1866 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1867 StringRef Value, types::ID Ty) {
1868 if (!D.getCheckInputsExist())
1871 // stdin always exists.
1875 SmallString<64> Path(Value);
1876 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1877 if (!llvm::sys::path::is_absolute(Path)) {
1878 SmallString<64> Directory(WorkDir->getValue());
1879 llvm::sys::path::append(Directory, Value);
1880 Path.assign(Directory);
1884 if (llvm::sys::fs::exists(Twine(Path)))
1888 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1889 llvm::sys::Process::FindInEnvPath("LIB", Value))
1892 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1893 // Arguments to the /link flag might cause the linker to search for object
1894 // and library files in paths we don't know about. Don't error in such
1900 D.Diag(clang::diag::err_drv_no_such_file) << Path;
1904 // Construct a the list of inputs and their types.
1905 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1906 InputList &Inputs) const {
1907 // Track the current user specified (-x) input. We also explicitly track the
1908 // argument used to set the type; we only want to claim the type when we
1909 // actually use it, so we warn about unused -x arguments.
1910 types::ID InputType = types::TY_Nothing;
1911 Arg *InputTypeArg = nullptr;
1913 // The last /TC or /TP option sets the input type to C or C++ globally.
1914 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1915 options::OPT__SLASH_TP)) {
1916 InputTypeArg = TCTP;
1917 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1921 Arg *Previous = nullptr;
1922 bool ShowNote = false;
1923 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1925 Diag(clang::diag::warn_drv_overriding_flag_option)
1926 << Previous->getSpelling() << A->getSpelling();
1932 Diag(clang::diag::note_drv_t_option_is_global);
1934 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1935 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1938 for (Arg *A : Args) {
1939 if (A->getOption().getKind() == Option::InputClass) {
1940 const char *Value = A->getValue();
1941 types::ID Ty = types::TY_INVALID;
1943 // Infer the input type if necessary.
1944 if (InputType == types::TY_Nothing) {
1945 // If there was an explicit arg for this, claim it.
1947 InputTypeArg->claim();
1949 // stdin must be handled specially.
1950 if (memcmp(Value, "-", 2) == 0) {
1951 // If running with -E, treat as a C input (this changes the builtin
1952 // macros, for example). This may be overridden by -ObjC below.
1954 // Otherwise emit an error but still use a valid type to avoid
1955 // spurious errors (e.g., no inputs).
1956 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1957 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1958 : clang::diag::err_drv_unknown_stdin_type);
1961 // Otherwise lookup by extension.
1962 // Fallback is C if invoked as C preprocessor or Object otherwise.
1963 // We use a host hook here because Darwin at least has its own
1964 // idea of what .s is.
1965 if (const char *Ext = strrchr(Value, '.'))
1966 Ty = TC.LookupTypeForExtension(Ext + 1);
1968 if (Ty == types::TY_INVALID) {
1972 Ty = types::TY_Object;
1975 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1976 // should autodetect some input files as C++ for g++ compatibility.
1978 types::ID OldTy = Ty;
1979 Ty = types::lookupCXXTypeForCType(Ty);
1982 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1983 << getTypeName(OldTy) << getTypeName(Ty);
1987 // -ObjC and -ObjC++ override the default language, but only for "source
1988 // files". We just treat everything that isn't a linker input as a
1991 // FIXME: Clean this up if we move the phase sequence into the type.
1992 if (Ty != types::TY_Object) {
1993 if (Args.hasArg(options::OPT_ObjC))
1994 Ty = types::TY_ObjC;
1995 else if (Args.hasArg(options::OPT_ObjCXX))
1996 Ty = types::TY_ObjCXX;
1999 assert(InputTypeArg && "InputType set w/o InputTypeArg");
2000 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2001 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2003 const char *Ext = strrchr(Value, '.');
2004 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2005 Ty = types::TY_Object;
2007 if (Ty == types::TY_INVALID) {
2009 InputTypeArg->claim();
2013 if (DiagnoseInputExistence(*this, Args, Value, Ty))
2014 Inputs.push_back(std::make_pair(Ty, A));
2016 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2017 StringRef Value = A->getValue();
2018 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
2019 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
2020 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2023 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2024 StringRef Value = A->getValue();
2025 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
2026 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
2027 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2030 } else if (A->getOption().hasFlag(options::LinkerInput)) {
2031 // Just treat as object type, we could make a special type for this if
2033 Inputs.push_back(std::make_pair(types::TY_Object, A));
2035 } else if (A->getOption().matches(options::OPT_x)) {
2037 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2040 // Follow gcc behavior and treat as linker input for invalid -x
2041 // options. Its not clear why we shouldn't just revert to unknown; but
2042 // this isn't very important, we might as well be bug compatible.
2044 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2045 InputType = types::TY_Object;
2047 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2048 assert(A->getNumValues() == 1 && "The /U option has one value.");
2049 StringRef Val = A->getValue(0);
2050 if (Val.find_first_of("/\\") != StringRef::npos) {
2051 // Warn about e.g. "/Users/me/myfile.c".
2052 Diag(diag::warn_slash_u_filename) << Val;
2053 Diag(diag::note_use_dashdash);
2057 if (CCCIsCPP() && Inputs.empty()) {
2058 // If called as standalone preprocessor, stdin is processed
2059 // if no other input is present.
2060 Arg *A = MakeInputArg(Args, *Opts, "-");
2061 Inputs.push_back(std::make_pair(types::TY_C, A));
2066 /// Provides a convenient interface for different programming models to generate
2067 /// the required device actions.
2068 class OffloadingActionBuilder final {
2069 /// Flag used to trace errors in the builder.
2070 bool IsValid = false;
2072 /// The compilation that is using this builder.
2075 /// Map between an input argument and the offload kinds used to process it.
2076 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2078 /// Builder interface. It doesn't build anything or keep any state.
2079 class DeviceActionBuilder {
2081 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2083 enum ActionBuilderReturnCode {
2084 // The builder acted successfully on the current action.
2086 // The builder didn't have to act on the current action.
2088 // The builder was successful and requested the host action to not be
2094 /// Compilation associated with this builder.
2097 /// Tool chains associated with this builder. The same programming
2098 /// model may have associated one or more tool chains.
2099 SmallVector<const ToolChain *, 2> ToolChains;
2101 /// The derived arguments associated with this builder.
2102 DerivedArgList &Args;
2104 /// The inputs associated with this builder.
2105 const Driver::InputList &Inputs;
2107 /// The associated offload kind.
2108 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2111 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2112 const Driver::InputList &Inputs,
2113 Action::OffloadKind AssociatedOffloadKind)
2114 : C(C), Args(Args), Inputs(Inputs),
2115 AssociatedOffloadKind(AssociatedOffloadKind) {}
2116 virtual ~DeviceActionBuilder() {}
2118 /// Fill up the array \a DA with all the device dependences that should be
2119 /// added to the provided host action \a HostAction. By default it is
2121 virtual ActionBuilderReturnCode
2122 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2123 phases::ID CurPhase, phases::ID FinalPhase,
2125 return ABRT_Inactive;
2128 /// Update the state to include the provided host action \a HostAction as a
2129 /// dependency of the current device action. By default it is inactive.
2130 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2131 return ABRT_Inactive;
2134 /// Append top level actions generated by the builder. Return true if errors
2136 virtual void appendTopLevelActions(ActionList &AL) {}
2138 /// Append linker actions generated by the builder. Return true if errors
2140 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2142 /// Initialize the builder. Return true if any initialization errors are
2144 virtual bool initialize() { return false; }
2146 /// Return true if the builder can use bundling/unbundling.
2147 virtual bool canUseBundlerUnbundler() const { return false; }
2149 /// Return true if this builder is valid. We have a valid builder if we have
2150 /// associated device tool chains.
2151 bool isValid() { return !ToolChains.empty(); }
2153 /// Return the associated offload kind.
2154 Action::OffloadKind getAssociatedOffloadKind() {
2155 return AssociatedOffloadKind;
2159 /// Base class for CUDA/HIP action builder. It injects device code in
2160 /// the host backend action.
2161 class CudaActionBuilderBase : public DeviceActionBuilder {
2163 /// Flags to signal if the user requested host-only or device-only
2165 bool CompileHostOnly = false;
2166 bool CompileDeviceOnly = false;
2168 /// List of GPU architectures to use in this compilation.
2169 SmallVector<CudaArch, 4> GpuArchList;
2171 /// The CUDA actions for the current input.
2172 ActionList CudaDeviceActions;
2174 /// The CUDA fat binary if it was generated for the current input.
2175 Action *CudaFatBinary = nullptr;
2177 /// Flag that is set to true if this builder acted on the current input.
2178 bool IsActive = false;
2180 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2181 const Driver::InputList &Inputs,
2182 Action::OffloadKind OFKind)
2183 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2185 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2186 // While generating code for CUDA, we only depend on the host input action
2187 // to trigger the creation of all the CUDA device actions.
2189 // If we are dealing with an input action, replicate it for each GPU
2190 // architecture. If we are in host-only mode we return 'success' so that
2191 // the host uses the CUDA offload kind.
2192 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2193 assert(!GpuArchList.empty() &&
2194 "We should have at least one GPU architecture.");
2196 // If the host input is not CUDA or HIP, we don't need to bother about
2198 if (IA->getType() != types::TY_CUDA &&
2199 IA->getType() != types::TY_HIP) {
2200 // The builder will ignore this input.
2202 return ABRT_Inactive;
2205 // Set the flag to true, so that the builder acts on the current input.
2208 if (CompileHostOnly)
2209 return ABRT_Success;
2211 // Replicate inputs for each GPU architecture.
2212 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2213 : types::TY_CUDA_DEVICE;
2214 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2215 CudaDeviceActions.push_back(
2216 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2219 return ABRT_Success;
2222 // If this is an unbundling action use it as is for each CUDA toolchain.
2223 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2224 CudaDeviceActions.clear();
2225 for (auto Arch : GpuArchList) {
2226 CudaDeviceActions.push_back(UA);
2227 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2228 AssociatedOffloadKind);
2230 return ABRT_Success;
2233 return IsActive ? ABRT_Success : ABRT_Inactive;
2236 void appendTopLevelActions(ActionList &AL) override {
2237 // Utility to append actions to the top level list.
2238 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2239 OffloadAction::DeviceDependences Dep;
2240 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2241 AssociatedOffloadKind);
2242 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2245 // If we have a fat binary, add it to the list.
2246 if (CudaFatBinary) {
2247 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2248 CudaDeviceActions.clear();
2249 CudaFatBinary = nullptr;
2253 if (CudaDeviceActions.empty())
2256 // If we have CUDA actions at this point, that's because we have a have
2257 // partial compilation, so we should have an action for each GPU
2259 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2260 "Expecting one action per GPU architecture.");
2261 assert(ToolChains.size() == 1 &&
2262 "Expecting to have a sing CUDA toolchain.");
2263 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2264 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2266 CudaDeviceActions.clear();
2269 bool initialize() override {
2270 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2271 AssociatedOffloadKind == Action::OFK_HIP);
2273 // We don't need to support CUDA.
2274 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2275 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2278 // We don't need to support HIP.
2279 if (AssociatedOffloadKind == Action::OFK_HIP &&
2280 !C.hasOffloadToolChain<Action::OFK_HIP>())
2283 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2284 assert(HostTC && "No toolchain for host compilation.");
2285 if (HostTC->getTriple().isNVPTX() ||
2286 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2287 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2288 // an error and abort pipeline construction early so we don't trip
2289 // asserts that assume device-side compilation.
2290 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2291 << HostTC->getTriple().getArchName();
2295 ToolChains.push_back(
2296 AssociatedOffloadKind == Action::OFK_Cuda
2297 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2298 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2300 Arg *PartialCompilationArg = Args.getLastArg(
2301 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2302 options::OPT_cuda_compile_host_device);
2303 CompileHostOnly = PartialCompilationArg &&
2304 PartialCompilationArg->getOption().matches(
2305 options::OPT_cuda_host_only);
2306 CompileDeviceOnly = PartialCompilationArg &&
2307 PartialCompilationArg->getOption().matches(
2308 options::OPT_cuda_device_only);
2310 // Collect all cuda_gpu_arch parameters, removing duplicates.
2311 std::set<CudaArch> GpuArchs;
2313 for (Arg *A : Args) {
2314 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2315 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2319 const StringRef ArchStr = A->getValue();
2320 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2325 CudaArch Arch = StringToCudaArch(ArchStr);
2326 if (Arch == CudaArch::UNKNOWN) {
2327 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2329 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2330 GpuArchs.insert(Arch);
2331 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2332 GpuArchs.erase(Arch);
2334 llvm_unreachable("Unexpected option.");
2337 // Collect list of GPUs remaining in the set.
2338 for (CudaArch Arch : GpuArchs)
2339 GpuArchList.push_back(Arch);
2341 // Default to sm_20 which is the lowest common denominator for
2342 // supported GPUs. sm_20 code should work correctly, if
2343 // suboptimally, on all newer GPUs.
2344 if (GpuArchList.empty())
2345 GpuArchList.push_back(CudaArch::SM_20);
2351 /// \brief CUDA action builder. It injects device code in the host backend
2353 class CudaActionBuilder final : public CudaActionBuilderBase {
2355 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2356 const Driver::InputList &Inputs)
2357 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
2359 ActionBuilderReturnCode
2360 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2361 phases::ID CurPhase, phases::ID FinalPhase,
2362 PhasesTy &Phases) override {
2364 return ABRT_Inactive;
2366 // If we don't have more CUDA actions, we don't have any dependences to
2367 // create for the host.
2368 if (CudaDeviceActions.empty())
2369 return ABRT_Success;
2371 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2372 "Expecting one action per GPU architecture.");
2373 assert(!CompileHostOnly &&
2374 "Not expecting CUDA actions in host-only compilation.");
2376 // If we are generating code for the device or we are in a backend phase,
2377 // we attempt to generate the fat binary. We compile each arch to ptx and
2378 // assemble to cubin, then feed the cubin *and* the ptx into a device
2379 // "link" action, which uses fatbinary to combine these cubins into one
2380 // fatbin. The fatbin is then an input to the host action if not in
2381 // device-only mode.
2382 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2383 ActionList DeviceActions;
2384 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2385 // Produce the device action from the current phase up to the assemble
2387 for (auto Ph : Phases) {
2388 // Skip the phases that were already dealt with.
2391 // We have to be consistent with the host final phase.
2392 if (Ph > FinalPhase)
2395 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2396 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
2398 if (Ph == phases::Assemble)
2402 // If we didn't reach the assemble phase, we can't generate the fat
2403 // binary. We don't need to generate the fat binary if we are not in
2404 // device-only mode.
2405 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2409 Action *AssembleAction = CudaDeviceActions[I];
2410 assert(AssembleAction->getType() == types::TY_Object);
2411 assert(AssembleAction->getInputs().size() == 1);
2413 Action *BackendAction = AssembleAction->getInputs()[0];
2414 assert(BackendAction->getType() == types::TY_PP_Asm);
2416 for (auto &A : {AssembleAction, BackendAction}) {
2417 OffloadAction::DeviceDependences DDep;
2418 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2420 DeviceActions.push_back(
2421 C.MakeAction<OffloadAction>(DDep, A->getType()));
2425 // We generate the fat binary if we have device input actions.
2426 if (!DeviceActions.empty()) {
2428 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2430 if (!CompileDeviceOnly) {
2431 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2433 // Clear the fat binary, it is already a dependence to an host
2435 CudaFatBinary = nullptr;
2438 // Remove the CUDA actions as they are already connected to an host
2439 // action or fat binary.
2440 CudaDeviceActions.clear();
2443 // We avoid creating host action in device-only mode.
2444 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2445 } else if (CurPhase > phases::Backend) {
2446 // If we are past the backend phase and still have a device action, we
2447 // don't have to do anything as this action is already a device
2448 // top-level action.
2449 return ABRT_Success;
2452 assert(CurPhase < phases::Backend && "Generating single CUDA "
2453 "instructions should only occur "
2454 "before the backend phase!");
2456 // By default, we produce an action for each device arch.
2457 for (Action *&A : CudaDeviceActions)
2458 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2460 return ABRT_Success;
2463 /// \brief HIP action builder. It injects device code in the host backend
2465 class HIPActionBuilder final : public CudaActionBuilderBase {
2466 /// The linker inputs obtained for each device arch.
2467 SmallVector<ActionList, 8> DeviceLinkerInputs;
2470 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2471 const Driver::InputList &Inputs)
2472 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {}
2474 bool canUseBundlerUnbundler() const override { return true; }
2476 ActionBuilderReturnCode
2477 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2478 phases::ID CurPhase, phases::ID FinalPhase,
2479 PhasesTy &Phases) override {
2480 // amdgcn does not support linking of object files, therefore we skip
2481 // backend and assemble phases to output LLVM IR.
2482 if (CudaDeviceActions.empty() || CurPhase == phases::Backend ||
2483 CurPhase == phases::Assemble)
2484 return ABRT_Success;
2486 assert((CurPhase == phases::Link ||
2487 CudaDeviceActions.size() == GpuArchList.size()) &&
2488 "Expecting one action per GPU architecture.");
2489 assert(!CompileHostOnly &&
2490 "Not expecting CUDA actions in host-only compilation.");
2492 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2493 // This happens to each device action originated from each input file.
2494 // Later on, device actions in DeviceLinkerInputs are used to create
2495 // device link actions in appendLinkDependences and the created device
2496 // link actions are passed to the offload action as device dependence.
2497 if (CurPhase == phases::Link) {
2498 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2499 auto LI = DeviceLinkerInputs.begin();
2500 for (auto *A : CudaDeviceActions) {
2505 // We will pass the device action as a host dependence, so we don't
2506 // need to do anything else with them.
2507 CudaDeviceActions.clear();
2508 return ABRT_Success;
2511 // By default, we produce an action for each device arch.
2512 for (Action *&A : CudaDeviceActions)
2513 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2514 AssociatedOffloadKind);
2516 return ABRT_Success;
2519 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2520 // Append a new link action for each device.
2522 for (auto &LI : DeviceLinkerInputs) {
2523 auto *DeviceLinkAction =
2524 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2525 DA.add(*DeviceLinkAction, *ToolChains[0],
2526 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2532 /// OpenMP action builder. The host bitcode is passed to the device frontend
2533 /// and all the device linked images are passed to the host link phase.
2534 class OpenMPActionBuilder final : public DeviceActionBuilder {
2535 /// The OpenMP actions for the current input.
2536 ActionList OpenMPDeviceActions;
2538 /// The linker inputs obtained for each toolchain.
2539 SmallVector<ActionList, 8> DeviceLinkerInputs;
2542 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2543 const Driver::InputList &Inputs)
2544 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2546 ActionBuilderReturnCode
2547 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2548 phases::ID CurPhase, phases::ID FinalPhase,
2549 PhasesTy &Phases) override {
2551 // We should always have an action for each input.
2552 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2553 "Number of OpenMP actions and toolchains do not match.");
2555 // The host only depends on device action in the linking phase, when all
2556 // the device images have to be embedded in the host image.
2557 if (CurPhase == phases::Link) {
2558 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2559 "Toolchains and linker inputs sizes do not match.");
2560 auto LI = DeviceLinkerInputs.begin();
2561 for (auto *A : OpenMPDeviceActions) {
2566 // We passed the device action as a host dependence, so we don't need to
2567 // do anything else with them.
2568 OpenMPDeviceActions.clear();
2569 return ABRT_Success;
2572 // By default, we produce an action for each device arch.
2573 for (Action *&A : OpenMPDeviceActions)
2574 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2576 return ABRT_Success;
2579 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2581 // If this is an input action replicate it for each OpenMP toolchain.
2582 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2583 OpenMPDeviceActions.clear();
2584 for (unsigned I = 0; I < ToolChains.size(); ++I)
2585 OpenMPDeviceActions.push_back(
2586 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2587 return ABRT_Success;
2590 // If this is an unbundling action use it as is for each OpenMP toolchain.
2591 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2592 OpenMPDeviceActions.clear();
2593 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2594 OpenMPDeviceActions.push_back(UA);
2595 UA->registerDependentActionInfo(
2596 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2598 return ABRT_Success;
2601 // When generating code for OpenMP we use the host compile phase result as
2602 // a dependence to the device compile phase so that it can learn what
2603 // declarations should be emitted. However, this is not the only use for
2604 // the host action, so we prevent it from being collapsed.
2605 if (isa<CompileJobAction>(HostAction)) {
2606 HostAction->setCannotBeCollapsedWithNextDependentAction();
2607 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2608 "Toolchains and device action sizes do not match.");
2609 OffloadAction::HostDependence HDep(
2610 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2611 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2612 auto TC = ToolChains.begin();
2613 for (Action *&A : OpenMPDeviceActions) {
2614 assert(isa<CompileJobAction>(A));
2615 OffloadAction::DeviceDependences DDep;
2616 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2617 A = C.MakeAction<OffloadAction>(HDep, DDep);
2621 return ABRT_Success;
2624 void appendTopLevelActions(ActionList &AL) override {
2625 if (OpenMPDeviceActions.empty())
2628 // We should always have an action for each input.
2629 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2630 "Number of OpenMP actions and toolchains do not match.");
2632 // Append all device actions followed by the proper offload action.
2633 auto TI = ToolChains.begin();
2634 for (auto *A : OpenMPDeviceActions) {
2635 OffloadAction::DeviceDependences Dep;
2636 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2637 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2640 // We no longer need the action stored in this builder.
2641 OpenMPDeviceActions.clear();
2644 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2645 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2646 "Toolchains and linker inputs sizes do not match.");
2648 // Append a new link action for each device.
2649 auto TC = ToolChains.begin();
2650 for (auto &LI : DeviceLinkerInputs) {
2651 auto *DeviceLinkAction =
2652 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2653 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2654 Action::OFK_OpenMP);
2659 bool initialize() override {
2660 // Get the OpenMP toolchains. If we don't get any, the action builder will
2661 // know there is nothing to do related to OpenMP offloading.
2662 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2663 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2665 ToolChains.push_back(TI->second);
2667 DeviceLinkerInputs.resize(ToolChains.size());
2671 bool canUseBundlerUnbundler() const override {
2672 // OpenMP should use bundled files whenever possible.
2678 /// TODO: Add the implementation for other specialized builders here.
2681 /// Specialized builders being used by this offloading action builder.
2682 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2684 /// Flag set to true if all valid builders allow file bundling/unbundling.
2688 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2689 const Driver::InputList &Inputs)
2691 // Create a specialized builder for each device toolchain.
2695 // Create a specialized builder for CUDA.
2696 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2698 // Create a specialized builder for HIP.
2699 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2701 // Create a specialized builder for OpenMP.
2702 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2705 // TODO: Build other specialized builders here.
2708 // Initialize all the builders, keeping track of errors. If all valid
2709 // builders agree that we can use bundling, set the flag to true.
2710 unsigned ValidBuilders = 0u;
2711 unsigned ValidBuildersSupportingBundling = 0u;
2712 for (auto *SB : SpecializedBuilders) {
2713 IsValid = IsValid && !SB->initialize();
2715 // Update the counters if the builder is valid.
2716 if (SB->isValid()) {
2718 if (SB->canUseBundlerUnbundler())
2719 ++ValidBuildersSupportingBundling;
2723 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
2726 ~OffloadingActionBuilder() {
2727 for (auto *SB : SpecializedBuilders)
2731 /// Generate an action that adds device dependences (if any) to a host action.
2732 /// If no device dependence actions exist, just return the host action \a
2733 /// HostAction. If an error is found or if no builder requires the host action
2734 /// to be generated, return nullptr.
2736 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2737 phases::ID CurPhase, phases::ID FinalPhase,
2738 DeviceActionBuilder::PhasesTy &Phases) {
2742 if (SpecializedBuilders.empty())
2745 assert(HostAction && "Invalid host action!");
2747 OffloadAction::DeviceDependences DDeps;
2748 // Check if all the programming models agree we should not emit the host
2749 // action. Also, keep track of the offloading kinds employed.
2750 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2751 unsigned InactiveBuilders = 0u;
2752 unsigned IgnoringBuilders = 0u;
2753 for (auto *SB : SpecializedBuilders) {
2754 if (!SB->isValid()) {
2760 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
2762 // If the builder explicitly says the host action should be ignored,
2763 // we need to increment the variable that tracks the builders that request
2764 // the host object to be ignored.
2765 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2768 // Unless the builder was inactive for this action, we have to record the
2769 // offload kind because the host will have to use it.
2770 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2771 OffloadKind |= SB->getAssociatedOffloadKind();
2774 // If all builders agree that the host object should be ignored, just return
2776 if (IgnoringBuilders &&
2777 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2780 if (DDeps.getActions().empty())
2783 // We have dependences we need to bundle together. We use an offload action
2785 OffloadAction::HostDependence HDep(
2786 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2787 /*BoundArch=*/nullptr, DDeps);
2788 return C.MakeAction<OffloadAction>(HDep, DDeps);
2791 /// Generate an action that adds a host dependence to a device action. The
2792 /// results will be kept in this action builder. Return true if an error was
2794 bool addHostDependenceToDeviceActions(Action *&HostAction,
2795 const Arg *InputArg) {
2799 // If we are supporting bundling/unbundling and the current action is an
2800 // input action of non-source file, we replace the host action by the
2801 // unbundling action. The bundler tool has the logic to detect if an input
2802 // is a bundle or not and if the input is not a bundle it assumes it is a
2803 // host file. Therefore it is safe to create an unbundling action even if
2804 // the input is not a bundle.
2805 if (CanUseBundler && isa<InputAction>(HostAction) &&
2806 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2807 !types::isSrcFile(HostAction->getType())) {
2808 auto UnbundlingHostAction =
2809 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2810 UnbundlingHostAction->registerDependentActionInfo(
2811 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2812 /*BoundArch=*/StringRef(), Action::OFK_Host);
2813 HostAction = UnbundlingHostAction;
2816 assert(HostAction && "Invalid host action!");
2818 // Register the offload kinds that are used.
2819 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2820 for (auto *SB : SpecializedBuilders) {
2824 auto RetCode = SB->addDeviceDepences(HostAction);
2826 // Host dependences for device actions are not compatible with that same
2827 // action being ignored.
2828 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2829 "Host dependence not expected to be ignored.!");
2831 // Unless the builder was inactive for this action, we have to record the
2832 // offload kind because the host will have to use it.
2833 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2834 OffloadKind |= SB->getAssociatedOffloadKind();
2840 /// Add the offloading top level actions to the provided action list. This
2841 /// function can replace the host action by a bundling action if the
2842 /// programming models allow it.
2843 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2844 const Arg *InputArg) {
2845 // Get the device actions to be appended.
2846 ActionList OffloadAL;
2847 for (auto *SB : SpecializedBuilders) {
2850 SB->appendTopLevelActions(OffloadAL);
2853 // If we can use the bundler, replace the host action by the bundling one in
2854 // the resulting list. Otherwise, just append the device actions.
2855 if (CanUseBundler && !OffloadAL.empty()) {
2856 // Add the host action to the list in order to create the bundling action.
2857 OffloadAL.push_back(HostAction);
2859 // We expect that the host action was just appended to the action list
2860 // before this method was called.
2861 assert(HostAction == AL.back() && "Host action not in the list??");
2862 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2863 AL.back() = HostAction;
2865 AL.append(OffloadAL.begin(), OffloadAL.end());
2867 // Propagate to the current host action (if any) the offload information
2868 // associated with the current input.
2870 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2871 /*BoundArch=*/nullptr);
2875 /// Processes the host linker action. This currently consists of replacing it
2876 /// with an offload action if there are device link objects and propagate to
2877 /// the host action all the offload kinds used in the current compilation. The
2878 /// resulting action is returned.
2879 Action *processHostLinkAction(Action *HostAction) {
2880 // Add all the dependences from the device linking actions.
2881 OffloadAction::DeviceDependences DDeps;
2882 for (auto *SB : SpecializedBuilders) {
2886 SB->appendLinkDependences(DDeps);
2889 // Calculate all the offload kinds used in the current compilation.
2890 unsigned ActiveOffloadKinds = 0u;
2891 for (auto &I : InputArgToOffloadKindMap)
2892 ActiveOffloadKinds |= I.second;
2894 // If we don't have device dependencies, we don't have to create an offload
2896 if (DDeps.getActions().empty()) {
2897 // Propagate all the active kinds to host action. Given that it is a link
2898 // action it is assumed to depend on all actions generated so far.
2899 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2900 /*BoundArch=*/nullptr);
2904 // Create the offload action with all dependences. When an offload action
2905 // is created the kinds are propagated to the host action, so we don't have
2906 // to do that explicitly here.
2907 OffloadAction::HostDependence HDep(
2908 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2909 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2910 return C.MakeAction<OffloadAction>(HDep, DDeps);
2913 } // anonymous namespace.
2915 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2916 const InputList &Inputs, ActionList &Actions) const {
2917 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
2919 if (!SuppressMissingInputWarning && Inputs.empty()) {
2920 Diag(clang::diag::err_drv_no_input_files);
2925 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
2927 if (FinalPhase == phases::Link) {
2928 if (Args.hasArg(options::OPT_emit_llvm))
2929 Diag(clang::diag::err_drv_emit_llvm_link);
2930 if (IsCLMode() && LTOMode != LTOK_None &&
2931 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2932 Diag(clang::diag::err_drv_lto_without_lld);
2935 // Reject -Z* at the top level, these options should never have been exposed
2937 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
2938 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
2940 // Diagnose misuse of /Fo.
2941 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
2942 StringRef V = A->getValue();
2943 if (Inputs.size() > 1 && !V.empty() &&
2944 !llvm::sys::path::is_separator(V.back())) {
2945 // Check whether /Fo tries to name an output file for multiple inputs.
2946 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2947 << A->getSpelling() << V;
2948 Args.eraseArg(options::OPT__SLASH_Fo);
2952 // Diagnose misuse of /Fa.
2953 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2954 StringRef V = A->getValue();
2955 if (Inputs.size() > 1 && !V.empty() &&
2956 !llvm::sys::path::is_separator(V.back())) {
2957 // Check whether /Fa tries to name an asm file for multiple inputs.
2958 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2959 << A->getSpelling() << V;
2960 Args.eraseArg(options::OPT__SLASH_Fa);
2964 // Diagnose misuse of /o.
2965 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2966 if (A->getValue()[0] == '\0') {
2967 // It has to have a value.
2968 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2969 Args.eraseArg(options::OPT__SLASH_o);
2973 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2974 // * no filename after it
2975 // * both /Yc and /Yu passed but with different filenames
2976 // * corresponding file not also passed as /FI
2977 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2978 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2979 if (YcArg && YcArg->getValue()[0] == '\0') {
2980 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2981 Args.eraseArg(options::OPT__SLASH_Yc);
2984 if (YuArg && YuArg->getValue()[0] == '\0') {
2985 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2986 Args.eraseArg(options::OPT__SLASH_Yu);
2989 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2990 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2991 Args.eraseArg(options::OPT__SLASH_Yc);
2992 Args.eraseArg(options::OPT__SLASH_Yu);
2993 YcArg = YuArg = nullptr;
2995 if (YcArg && Inputs.size() > 1) {
2996 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2997 Args.eraseArg(options::OPT__SLASH_Yc);
3000 if (Args.hasArg(options::OPT__SLASH_Y_)) {
3001 // /Y- disables all pch handling. Rather than check for it everywhere,
3002 // just remove clang-cl pch-related flags here.
3003 Args.eraseArg(options::OPT__SLASH_Fp);
3004 Args.eraseArg(options::OPT__SLASH_Yc);
3005 Args.eraseArg(options::OPT__SLASH_Yu);
3006 YcArg = YuArg = nullptr;
3009 // Builder to be used to build offloading actions.
3010 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3012 // Construct the actions to perform.
3013 ActionList LinkerInputs;
3015 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
3016 for (auto &I : Inputs) {
3017 types::ID InputType = I.first;
3018 const Arg *InputArg = I.second;
3021 types::getCompilationPhases(InputType, PL);
3023 // If the first step comes after the final phase we are doing as part of
3024 // this compilation, warn the user about it.
3025 phases::ID InitialPhase = PL[0];
3026 if (InitialPhase > FinalPhase) {
3027 if (InputArg->isClaimed())
3030 // Claim here to avoid the more general unused warning.
3033 // Suppress all unused style warnings with -Qunused-arguments
3034 if (Args.hasArg(options::OPT_Qunused_arguments))
3037 // Special case when final phase determined by binary name, rather than
3038 // by a command-line argument with a corresponding Arg.
3040 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3041 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3042 // Special case '-E' warning on a previously preprocessed file to make
3044 else if (InitialPhase == phases::Compile &&
3045 FinalPhase == phases::Preprocess &&
3046 getPreprocessedType(InputType) == types::TY_INVALID)
3047 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3048 << InputArg->getAsString(Args) << !!FinalPhaseArg
3049 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3051 Diag(clang::diag::warn_drv_input_file_unused)
3052 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3054 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3059 // Add a separate precompile phase for the compile phase.
3060 if (FinalPhase >= phases::Compile) {
3061 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3062 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
3063 types::getCompilationPhases(HeaderType, PCHPL);
3064 // Build the pipeline for the pch file.
3065 Action *ClangClPch =
3066 C.MakeAction<InputAction>(*InputArg, HeaderType);
3067 for (phases::ID Phase : PCHPL)
3068 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3070 Actions.push_back(ClangClPch);
3071 // The driver currently exits after the first failed command. This
3072 // relies on that behavior, to make sure if the pch generation fails,
3073 // the main compilation won't run.
3074 // FIXME: If the main compilation fails, the PCH generation should
3075 // probably not be considered successful either.
3079 // Build the pipeline for this file.
3080 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3082 // Use the current host action in any of the offloading actions, if
3084 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3087 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3089 phases::ID Phase = *i;
3091 // We are done if this step is past what the user requested.
3092 if (Phase > FinalPhase)
3095 // Add any offload action the host action depends on.
3096 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3097 Current, InputArg, Phase, FinalPhase, PL);
3101 // Queue linker inputs.
3102 if (Phase == phases::Link) {
3103 assert((i + 1) == e && "linking must be final compilation step.");
3104 LinkerInputs.push_back(Current);
3109 // Otherwise construct the appropriate action.
3110 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3112 // We didn't create a new action, so we will just move to the next phase.
3113 if (NewCurrent == Current)
3116 Current = NewCurrent;
3118 // Use the current host action in any of the offloading actions, if
3120 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3123 if (Current->getType() == types::TY_Nothing)
3127 // If we ended with something, add to the output list.
3129 Actions.push_back(Current);
3131 // Add any top level actions generated for offloading.
3132 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3135 // Add a link action if necessary.
3136 if (!LinkerInputs.empty()) {
3137 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3138 LA = OffloadBuilder.processHostLinkAction(LA);
3139 Actions.push_back(LA);
3142 // If we are linking, claim any options which are obviously only used for
3144 if (FinalPhase == phases::Link && PL.size() == 1) {
3145 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3146 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3149 // Claim ignored clang-cl options.
3150 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3152 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3153 // to non-CUDA compilations and should not trigger warnings there.
3154 Args.ClaimAllArgs(options::OPT_cuda_host_only);
3155 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3158 Action *Driver::ConstructPhaseAction(
3159 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3160 Action::OffloadKind TargetDeviceOffloadKind) const {
3161 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3163 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3164 // encode this in the steps because the intermediate type depends on
3165 // arguments. Just special case here.
3166 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3169 // Build the appropriate action.
3172 llvm_unreachable("link action invalid here.");
3173 case phases::Preprocess: {
3175 // -{M, MM} alter the output type.
3176 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
3177 OutputTy = types::TY_Dependencies;
3179 OutputTy = Input->getType();
3180 if (!Args.hasFlag(options::OPT_frewrite_includes,
3181 options::OPT_fno_rewrite_includes, false) &&
3182 !Args.hasFlag(options::OPT_frewrite_imports,
3183 options::OPT_fno_rewrite_imports, false) &&
3185 OutputTy = types::getPreprocessedType(OutputTy);
3186 assert(OutputTy != types::TY_INVALID &&
3187 "Cannot preprocess this input type!");
3189 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3191 case phases::Precompile: {
3192 types::ID OutputTy = getPrecompiledType(Input->getType());
3193 assert(OutputTy != types::TY_INVALID &&
3194 "Cannot precompile this input type!");
3195 if (Args.hasArg(options::OPT_fsyntax_only)) {
3196 // Syntax checks should not emit a PCH file
3197 OutputTy = types::TY_Nothing;
3199 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3201 case phases::Compile: {
3202 if (Args.hasArg(options::OPT_fsyntax_only))
3203 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3204 if (Args.hasArg(options::OPT_rewrite_objc))
3205 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3206 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3207 return C.MakeAction<CompileJobAction>(Input,
3208 types::TY_RewrittenLegacyObjC);
3209 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
3210 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3211 if (Args.hasArg(options::OPT__migrate))
3212 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3213 if (Args.hasArg(options::OPT_emit_ast))
3214 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3215 if (Args.hasArg(options::OPT_module_file_info))
3216 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3217 if (Args.hasArg(options::OPT_verify_pch))
3218 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3219 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3221 case phases::Backend: {
3222 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
3224 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
3225 return C.MakeAction<BackendJobAction>(Input, Output);
3227 if (Args.hasArg(options::OPT_emit_llvm)) {
3229 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
3230 return C.MakeAction<BackendJobAction>(Input, Output);
3232 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
3234 case phases::Assemble:
3235 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
3238 llvm_unreachable("invalid phase in ConstructPhaseAction");
3241 void Driver::BuildJobs(Compilation &C) const {
3242 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3244 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3246 // It is an error to provide a -o option if we are making multiple output
3249 unsigned NumOutputs = 0;
3250 for (const Action *A : C.getActions())
3251 if (A->getType() != types::TY_Nothing)
3254 if (NumOutputs > 1) {
3255 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
3256 FinalOutput = nullptr;
3260 // Collect the list of architectures.
3261 llvm::StringSet<> ArchNames;
3262 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3263 for (const Arg *A : C.getArgs())
3264 if (A->getOption().matches(options::OPT_arch))
3265 ArchNames.insert(A->getValue());
3267 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3268 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
3269 for (Action *A : C.getActions()) {
3270 // If we are linking an image for multiple archs then the linker wants
3271 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3272 // doesn't fit in cleanly because we have to pass this information down.
3274 // FIXME: This is a hack; find a cleaner way to integrate this into the
3276 const char *LinkingOutput = nullptr;
3277 if (isa<LipoJobAction>(A)) {
3279 LinkingOutput = FinalOutput->getValue();
3281 LinkingOutput = getDefaultImageName();
3284 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
3285 /*BoundArch*/ StringRef(),
3286 /*AtTopLevel*/ true,
3287 /*MultipleArchs*/ ArchNames.size() > 1,
3288 /*LinkingOutput*/ LinkingOutput, CachedResults,
3289 /*TargetDeviceOffloadKind*/ Action::OFK_None);
3292 // If the user passed -Qunused-arguments or there were errors, don't warn
3293 // about any unused arguments.
3294 if (Diags.hasErrorOccurred() ||
3295 C.getArgs().hasArg(options::OPT_Qunused_arguments))
3299 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
3301 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
3302 (void)C.getArgs().hasArg(options::OPT_driver_mode);
3303 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
3305 for (Arg *A : C.getArgs()) {
3306 // FIXME: It would be nice to be able to send the argument to the
3307 // DiagnosticsEngine, so that extra values, position, and so on could be
3309 if (!A->isClaimed()) {
3310 if (A->getOption().hasFlag(options::NoArgumentUnused))
3313 // Suppress the warning automatically if this is just a flag, and it is an
3314 // instance of an argument we already claimed.
3315 const Option &Opt = A->getOption();
3316 if (Opt.getKind() == Option::FlagClass) {
3317 bool DuplicateClaimed = false;
3319 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3320 if (AA->isClaimed()) {
3321 DuplicateClaimed = true;
3326 if (DuplicateClaimed)
3330 // In clang-cl, don't mention unknown arguments here since they have
3331 // already been warned about.
3332 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3333 Diag(clang::diag::warn_drv_unused_argument)
3334 << A->getAsString(C.getArgs());
3340 /// Utility class to control the collapse of dependent actions and select the
3341 /// tools accordingly.
3342 class ToolSelector final {
3343 /// The tool chain this selector refers to.
3344 const ToolChain &TC;
3346 /// The compilation this selector refers to.
3347 const Compilation &C;
3349 /// The base action this selector refers to.
3350 const JobAction *BaseAction;
3352 /// Set to true if the current toolchain refers to host actions.
3353 bool IsHostSelector;
3355 /// Set to true if save-temps and embed-bitcode functionalities are active.
3359 /// Get previous dependent action or null if that does not exist. If
3360 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3361 /// null will be returned.
3362 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3363 ActionList &SavedOffloadAction,
3364 bool CanBeCollapsed = true) {
3365 // An option can be collapsed only if it has a single input.
3366 if (Inputs.size() != 1)
3369 Action *CurAction = *Inputs.begin();
3370 if (CanBeCollapsed &&
3371 !CurAction->isCollapsingWithNextDependentActionLegal())
3374 // If the input action is an offload action. Look through it and save any
3375 // offload action that can be dropped in the event of a collapse.
3376 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3377 // If the dependent action is a device action, we will attempt to collapse
3378 // only with other device actions. Otherwise, we would do the same but
3379 // with host actions only.
3380 if (!IsHostSelector) {
3381 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3383 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3384 if (CanBeCollapsed &&
3385 !CurAction->isCollapsingWithNextDependentActionLegal())
3387 SavedOffloadAction.push_back(OA);
3388 return dyn_cast<JobAction>(CurAction);
3390 } else if (OA->hasHostDependence()) {
3391 CurAction = OA->getHostDependence();
3392 if (CanBeCollapsed &&
3393 !CurAction->isCollapsingWithNextDependentActionLegal())
3395 SavedOffloadAction.push_back(OA);
3396 return dyn_cast<JobAction>(CurAction);
3401 return dyn_cast<JobAction>(CurAction);
3404 /// Return true if an assemble action can be collapsed.
3405 bool canCollapseAssembleAction() const {
3406 return TC.useIntegratedAs() && !SaveTemps &&
3407 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3408 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3409 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3412 /// Return true if a preprocessor action can be collapsed.
3413 bool canCollapsePreprocessorAction() const {
3414 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3415 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3416 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3419 /// Struct that relates an action with the offload actions that would be
3420 /// collapsed with it.
3421 struct JobActionInfo final {
3422 /// The action this info refers to.
3423 const JobAction *JA = nullptr;
3424 /// The offload actions we need to take care off if this action is
3426 ActionList SavedOffloadAction;
3429 /// Append collapsed offload actions from the give nnumber of elements in the
3430 /// action info array.
3431 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3432 ArrayRef<JobActionInfo> &ActionInfo,
3433 unsigned ElementNum) {
3434 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3435 for (unsigned I = 0; I < ElementNum; ++I)
3436 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3437 ActionInfo[I].SavedOffloadAction.end());
3440 /// Functions that attempt to perform the combining. They detect if that is
3441 /// legal, and if so they update the inputs \a Inputs and the offload action
3442 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3443 /// the combined action is returned. If the combining is not legal or if the
3444 /// tool does not exist, null is returned.
3445 /// Currently three kinds of collapsing are supported:
3446 /// - Assemble + Backend + Compile;
3447 /// - Assemble + Backend ;
3448 /// - Backend + Compile.
3450 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3451 const ActionList *&Inputs,
3452 ActionList &CollapsedOffloadAction) {
3453 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3455 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3456 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3457 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3458 if (!AJ || !BJ || !CJ)
3461 // Get compiler tool.
3462 const Tool *T = TC.SelectTool(*CJ);
3466 // When using -fembed-bitcode, it is required to have the same tool (clang)
3467 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3469 const Tool *BT = TC.SelectTool(*BJ);
3474 if (!T->hasIntegratedAssembler())
3477 Inputs = &CJ->getInputs();
3478 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3482 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3483 const ActionList *&Inputs,
3484 ActionList &CollapsedOffloadAction) {
3485 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3487 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3488 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3492 // Retrieve the compile job, backend action must always be preceded by one.
3493 ActionList CompileJobOffloadActions;
3494 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3495 /*CanBeCollapsed=*/false);
3496 if (!AJ || !BJ || !CJ)
3499 assert(isa<CompileJobAction>(CJ) &&
3500 "Expecting compile job preceding backend job.");
3502 // Get compiler tool.
3503 const Tool *T = TC.SelectTool(*CJ);
3507 if (!T->hasIntegratedAssembler())
3510 Inputs = &BJ->getInputs();
3511 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3515 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3516 const ActionList *&Inputs,
3517 ActionList &CollapsedOffloadAction) {
3518 if (ActionInfo.size() < 2)
3520 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3521 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3525 // Check if the initial input (to the compile job or its predessor if one
3526 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3527 // and we can still collapse the compile and backend jobs when we have
3528 // -save-temps. I.e. there is no need for a separate compile job just to
3529 // emit unoptimized bitcode.
3530 bool InputIsBitcode = true;
3531 for (size_t i = 1; i < ActionInfo.size(); i++)
3532 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3533 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3534 InputIsBitcode = false;
3537 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3540 // Get compiler tool.
3541 const Tool *T = TC.SelectTool(*CJ);
3545 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
3548 Inputs = &CJ->getInputs();
3549 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3554 /// Updates the inputs if the obtained tool supports combining with
3555 /// preprocessor action, and the current input is indeed a preprocessor
3556 /// action. If combining results in the collapse of offloading actions, those
3557 /// are appended to \a CollapsedOffloadAction.
3558 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3559 ActionList &CollapsedOffloadAction) {
3560 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3563 // Attempt to get a preprocessor action dependence.
3564 ActionList PreprocessJobOffloadActions;
3565 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3566 if (!PJ || !isa<PreprocessJobAction>(PJ))
3569 // This is legal to combine. Append any offload action we found and set the
3570 // current inputs to preprocessor inputs.
3571 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3572 PreprocessJobOffloadActions.end());
3573 Inputs = &PJ->getInputs();
3577 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3578 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3579 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3580 EmbedBitcode(EmbedBitcode) {
3581 assert(BaseAction && "Invalid base action.");
3582 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3585 /// Check if a chain of actions can be combined and return the tool that can
3586 /// handle the combination of actions. The pointer to the current inputs \a
3587 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3588 /// connected to collapsed actions are updated accordingly. The latter enables
3589 /// the caller of the selector to process them afterwards instead of just
3590 /// dropping them. If no suitable tool is found, null will be returned.
3591 const Tool *getTool(const ActionList *&Inputs,
3592 ActionList &CollapsedOffloadAction) {
3594 // Get the largest chain of actions that we could combine.
3597 SmallVector<JobActionInfo, 5> ActionChain(1);
3598 ActionChain.back().JA = BaseAction;
3599 while (ActionChain.back().JA) {
3600 const Action *CurAction = ActionChain.back().JA;
3602 // Grow the chain by one element.
3603 ActionChain.resize(ActionChain.size() + 1);
3604 JobActionInfo &AI = ActionChain.back();
3606 // Attempt to fill it with the
3608 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
3611 // Pop the last action info as it could not be filled.
3612 ActionChain.pop_back();
3615 // Attempt to combine actions. If all combining attempts failed, just return
3616 // the tool of the provided action. At the end we attempt to combine the
3617 // action with any preprocessor action it may depend on.
3620 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3621 CollapsedOffloadAction);
3623 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3625 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3627 Inputs = &BaseAction->getInputs();
3628 T = TC.SelectTool(*BaseAction);
3631 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3637 /// Return a string that uniquely identifies the result of a job. The bound arch
3638 /// is not necessarily represented in the toolchain's triple -- for example,
3639 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
3640 /// Also, we need to add the offloading device kind, as the same tool chain can
3641 /// be used for host and device for some programming models, e.g. OpenMP.
3642 static std::string GetTriplePlusArchString(const ToolChain *TC,
3643 StringRef BoundArch,
3644 Action::OffloadKind OffloadKind) {
3645 std::string TriplePlusArch = TC->getTriple().normalize();
3646 if (!BoundArch.empty()) {
3647 TriplePlusArch += "-";
3648 TriplePlusArch += BoundArch;
3650 TriplePlusArch += "-";
3651 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3652 return TriplePlusArch;
3655 InputInfo Driver::BuildJobsForAction(
3656 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3657 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3658 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3659 Action::OffloadKind TargetDeviceOffloadKind) const {
3660 std::pair<const Action *, std::string> ActionTC = {
3661 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3662 auto CachedResult = CachedResults.find(ActionTC);
3663 if (CachedResult != CachedResults.end()) {
3664 return CachedResult->second;
3666 InputInfo Result = BuildJobsForActionNoCache(
3667 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
3668 CachedResults, TargetDeviceOffloadKind);
3669 CachedResults[ActionTC] = Result;
3673 InputInfo Driver::BuildJobsForActionNoCache(
3674 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3675 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3676 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3677 Action::OffloadKind TargetDeviceOffloadKind) const {
3678 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3680 InputInfoList OffloadDependencesInputInfo;
3681 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
3682 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3683 // The 'Darwin' toolchain is initialized only when its arguments are
3684 // computed. Get the default arguments for OFK_None to ensure that
3685 // initialization is performed before processing the offload action.
3686 // FIXME: Remove when darwin's toolchain is initialized during construction.
3687 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3689 // The offload action is expected to be used in four different situations.
3691 // a) Set a toolchain/architecture/kind for a host action:
3692 // Host Action 1 -> OffloadAction -> Host Action 2
3694 // b) Set a toolchain/architecture/kind for a device action;
3695 // Device Action 1 -> OffloadAction -> Device Action 2
3697 // c) Specify a device dependence to a host action;
3698 // Device Action 1 _
3700 // Host Action 1 ---> OffloadAction -> Host Action 2
3702 // d) Specify a host dependence to a device action.
3705 // Device Action 1 ---> OffloadAction -> Device Action 2
3707 // For a) and b), we just return the job generated for the dependence. For
3708 // c) and d) we override the current action with the host/device dependence
3709 // if the current toolchain is host/device and set the offload dependences
3710 // info with the jobs obtained from the device/host dependence(s).
3712 // If there is a single device option, just generate the job for it.
3713 if (OA->hasSingleDeviceDependence()) {
3715 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3716 const char *DepBoundArch) {
3718 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3719 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
3720 CachedResults, DepA->getOffloadingDeviceKind());
3725 // If 'Action 2' is host, we generate jobs for the device dependences and
3726 // override the current action with the host dependence. Otherwise, we
3727 // generate the host dependences and override the action with the device
3728 // dependence. The dependences can't therefore be a top-level action.
3729 OA->doOnEachDependence(
3730 /*IsHostDependence=*/BuildingForOffloadDevice,
3731 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3732 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3733 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3734 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
3735 DepA->getOffloadingDeviceKind()));
3738 A = BuildingForOffloadDevice
3739 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3740 : OA->getHostDependence();
3743 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
3744 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3745 // just using Args was better?
3746 const Arg &Input = IA->getInputArg();
3748 if (Input.getOption().matches(options::OPT_INPUT)) {
3749 const char *Name = Input.getValue();
3750 return InputInfo(A, Name, /* BaseInput = */ Name);
3752 return InputInfo(A, &Input, /* BaseInput = */ "");
3755 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
3756 const ToolChain *TC;
3757 StringRef ArchName = BAA->getArchName();
3759 if (!ArchName.empty())
3760 TC = &getToolChain(C.getArgs(),
3761 computeTargetTriple(*this, TargetTriple,
3762 C.getArgs(), ArchName));
3764 TC = &C.getDefaultToolChain();
3766 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
3767 MultipleArchs, LinkingOutput, CachedResults,
3768 TargetDeviceOffloadKind);
3772 const ActionList *Inputs = &A->getInputs();
3774 const JobAction *JA = cast<JobAction>(A);
3775 ActionList CollapsedOffloadActions;
3777 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3778 embedBitcodeInObject() && !isUsingLTO());
3779 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3784 // If we've collapsed action list that contained OffloadAction we
3785 // need to build jobs for host/device-side inputs it may have held.
3786 for (const auto *OA : CollapsedOffloadActions)
3787 cast<OffloadAction>(OA)->doOnEachDependence(
3788 /*IsHostDependence=*/BuildingForOffloadDevice,
3789 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3790 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3791 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
3792 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
3793 DepA->getOffloadingDeviceKind()));
3796 // Only use pipes when there is exactly one input.
3797 InputInfoList InputInfos;
3798 for (const Action *Input : *Inputs) {
3799 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3800 // shouldn't get temporary output names.
3801 // FIXME: Clean this up.
3802 bool SubJobAtTopLevel =
3803 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
3804 InputInfos.push_back(BuildJobsForAction(
3805 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
3806 CachedResults, A->getOffloadingDeviceKind()));
3809 // Always use the first input as the base input.
3810 const char *BaseInput = InputInfos[0].getBaseInput();
3812 // ... except dsymutil actions, which use their actual input as the base
3814 if (JA->getType() == types::TY_dSYM)
3815 BaseInput = InputInfos[0].getFilename();
3817 // Append outputs of offload device jobs to the input list
3818 if (!OffloadDependencesInputInfo.empty())
3819 InputInfos.append(OffloadDependencesInputInfo.begin(),
3820 OffloadDependencesInputInfo.end());
3822 // Set the effective triple of the toolchain for the duration of this job.
3823 llvm::Triple EffectiveTriple;
3824 const ToolChain &ToolTC = T->getToolChain();
3825 const ArgList &Args =
3826 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
3827 if (InputInfos.size() != 1) {
3828 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3830 // Pass along the input type if it can be unambiguously determined.
3831 EffectiveTriple = llvm::Triple(
3832 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3834 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3836 // Determine the place to write output to, if any.
3838 InputInfoList UnbundlingResults;
3839 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3840 // If we have an unbundling job, we need to create results for all the
3841 // outputs. We also update the results cache so that other actions using
3842 // this unbundling action can get the right results.
3843 for (auto &UI : UA->getDependentActionsInfo()) {
3844 assert(UI.DependentOffloadKind != Action::OFK_None &&
3845 "Unbundling with no offloading??");
3847 // Unbundling actions are never at the top level. When we generate the
3848 // offloading prefix, we also do that for the host file because the
3849 // unbundling action does not change the type of the output which can
3850 // cause a overwrite.
3851 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3852 UI.DependentOffloadKind,
3853 UI.DependentToolChain->getTriple().normalize(),
3854 /*CreatePrefixForHost=*/true);
3855 auto CurI = InputInfo(
3857 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3858 /*AtTopLevel=*/false,
3860 UI.DependentOffloadKind == Action::OFK_HIP,
3863 // Save the unbundling result.
3864 UnbundlingResults.push_back(CurI);
3866 // Get the unique string identifier for this dependence and cache the
3869 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
3870 if (UI.DependentOffloadKind == Action::OFK_Host)
3873 Arch = UI.DependentBoundArch;
3877 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
3878 UI.DependentOffloadKind)}] =
3882 // Now that we have all the results generated, select the one that should be
3883 // returned for the current depending action.
3884 std::pair<const Action *, std::string> ActionTC = {
3885 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3886 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3887 "Result does not exist??");
3888 Result = CachedResults[ActionTC];
3889 } else if (JA->getType() == types::TY_Nothing)
3890 Result = InputInfo(A, BaseInput);
3892 // We only have to generate a prefix for the host if this is not a top-level
3894 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3895 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3896 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3898 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
3899 AtTopLevel, MultipleArchs,
3904 if (CCCPrintBindings && !CCGenDiagnostics) {
3905 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3906 << " - \"" << T->getName() << "\", inputs: [";
3907 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3908 llvm::errs() << InputInfos[i].getAsString();
3910 llvm::errs() << ", ";
3912 if (UnbundlingResults.empty())
3913 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3915 llvm::errs() << "], outputs: [";
3916 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3917 llvm::errs() << UnbundlingResults[i].getAsString();
3919 llvm::errs() << ", ";
3921 llvm::errs() << "] \n";
3924 if (UnbundlingResults.empty())
3926 C, *JA, Result, InputInfos,
3927 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3930 T->ConstructJobMultipleOutputs(
3931 C, *JA, UnbundlingResults, InputInfos,
3932 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3938 const char *Driver::getDefaultImageName() const {
3939 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
3940 return Target.isOSWindows() ? "a.exe" : "a.out";
3943 /// Create output filename based on ArgValue, which could either be a
3944 /// full filename, filename without extension, or a directory. If ArgValue
3945 /// does not provide a filename, then use BaseName, and use the extension
3946 /// suitable for FileType.
3947 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
3949 types::ID FileType) {
3950 SmallString<128> Filename = ArgValue;
3952 if (ArgValue.empty()) {
3953 // If the argument is empty, output to BaseName in the current dir.
3954 Filename = BaseName;
3955 } else if (llvm::sys::path::is_separator(Filename.back())) {
3956 // If the argument is a directory, output to BaseName in that dir.
3957 llvm::sys::path::append(Filename, BaseName);
3960 if (!llvm::sys::path::has_extension(ArgValue)) {
3961 // If the argument didn't provide an extension, then set it.
3962 const char *Extension = types::getTypeTempSuffix(FileType, true);
3964 if (FileType == types::TY_Image &&
3965 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3966 // The output file is a dll.
3970 llvm::sys::path::replace_extension(Filename, Extension);
3973 return Args.MakeArgString(Filename.c_str());
3976 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
3977 const char *BaseInput,
3978 StringRef BoundArch, bool AtTopLevel,
3980 StringRef OffloadingPrefix) const {
3981 llvm::PrettyStackTraceString CrashInfo("Computing output path");
3982 // Output to a user requested destination?
3983 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
3984 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
3985 return C.addResultFile(FinalOutput->getValue(), &JA);
3988 // For /P, preprocess to file named after BaseInput.
3989 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3990 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3991 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3993 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
3994 NameArg = A->getValue();
3995 return C.addResultFile(
3996 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4000 // Default to writing to stdout?
4001 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
4004 // Is this the assembly listing for /FA?
4005 if (JA.getType() == types::TY_PP_Asm &&
4006 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4007 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4008 // Use /Fa and the input filename to determine the asm file name.
4009 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4010 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4011 return C.addResultFile(
4012 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4016 // Output to a temporary file?
4017 if ((!AtTopLevel && !isSaveTempsEnabled() &&
4018 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4020 StringRef Name = llvm::sys::path::filename(BaseInput);
4021 std::pair<StringRef, StringRef> Split = Name.split('.');
4022 SmallString<128> TmpName;
4023 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4024 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4025 if (CCGenDiagnostics && A) {
4026 SmallString<128> CrashDirectory(A->getValue());
4027 llvm::sys::path::append(CrashDirectory, Split.first);
4028 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4029 std::error_code EC =
4030 llvm::sys::fs::createUniqueFile(CrashDirectory + Middle + Suffix, TmpName);
4032 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4036 TmpName = GetTemporaryPath(Split.first, Suffix);
4038 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4041 SmallString<128> BasePath(BaseInput);
4044 // Dsymutil actions should use the full path.
4045 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
4046 BaseName = BasePath;
4048 BaseName = llvm::sys::path::filename(BasePath);
4050 // Determine what the derived output name should be.
4051 const char *NamedOutput;
4053 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
4054 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4055 // The /Fo or /o flag decides the object filename.
4058 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4061 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4062 } else if (JA.getType() == types::TY_Image &&
4063 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4064 options::OPT__SLASH_o)) {
4065 // The /Fe or /o flag names the linked file.
4068 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4071 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
4072 } else if (JA.getType() == types::TY_Image) {
4074 // clang-cl uses BaseName for the executable name.
4076 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
4078 SmallString<128> Output(getDefaultImageName());
4079 Output += OffloadingPrefix;
4080 if (MultipleArchs && !BoundArch.empty()) {
4082 Output.append(BoundArch);
4084 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
4086 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
4087 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
4089 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4090 assert(Suffix && "All types used for output should have a suffix.");
4092 std::string::size_type End = std::string::npos;
4093 if (!types::appendSuffixForType(JA.getType()))
4094 End = BaseName.rfind('.');
4095 SmallString<128> Suffixed(BaseName.substr(0, End));
4096 Suffixed += OffloadingPrefix;
4097 if (MultipleArchs && !BoundArch.empty()) {
4099 Suffixed.append(BoundArch);
4101 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4102 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4103 // optimized bitcode output.
4104 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4105 JA.getType() == types::TY_LLVM_BC)
4109 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4112 // Prepend object file path if -save-temps=obj
4113 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4114 JA.getType() != types::TY_PCH) {
4115 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4116 SmallString<128> TempPath(FinalOutput->getValue());
4117 llvm::sys::path::remove_filename(TempPath);
4118 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4119 llvm::sys::path::append(TempPath, OutputFileName);
4120 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4123 // If we're saving temps and the temp file conflicts with the input file,
4124 // then avoid overwriting input file.
4125 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
4126 bool SameFile = false;
4127 SmallString<256> Result;
4128 llvm::sys::fs::current_path(Result);
4129 llvm::sys::path::append(Result, BaseName);
4130 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4131 // Must share the same path to conflict.
4133 StringRef Name = llvm::sys::path::filename(BaseInput);
4134 std::pair<StringRef, StringRef> Split = Name.split('.');
4135 std::string TmpName = GetTemporaryPath(
4136 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
4137 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4141 // As an annoying special case, PCH generation doesn't strip the pathname.
4142 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
4143 llvm::sys::path::remove_filename(BasePath);
4144 if (BasePath.empty())
4145 BasePath = NamedOutput;
4147 llvm::sys::path::append(BasePath, NamedOutput);
4148 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
4150 return C.addResultFile(NamedOutput, &JA);
4154 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
4155 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4156 // attempting to use this prefix when looking for file paths.
4157 for (const std::string &Dir : PrefixDirs) {
4160 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4161 llvm::sys::path::append(P, Name);
4162 if (llvm::sys::fs::exists(Twine(P)))
4166 SmallString<128> R(ResourceDir);
4167 llvm::sys::path::append(R, Name);
4168 if (llvm::sys::fs::exists(Twine(R)))
4171 SmallString<128> P(TC.getCompilerRTPath());
4172 llvm::sys::path::append(P, Name);
4173 if (llvm::sys::fs::exists(Twine(P)))
4176 for (const std::string &Dir : TC.getFilePaths()) {
4179 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4180 llvm::sys::path::append(P, Name);
4181 if (llvm::sys::fs::exists(Twine(P)))
4188 void Driver::generatePrefixedToolNames(
4189 StringRef Tool, const ToolChain &TC,
4190 SmallVectorImpl<std::string> &Names) const {
4191 // FIXME: Needs a better variable than TargetTriple
4192 Names.emplace_back((TargetTriple + "-" + Tool).str());
4193 Names.emplace_back(Tool);
4195 // Allow the discovery of tools prefixed with LLVM's default target triple.
4196 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4197 if (DefaultTargetTriple != TargetTriple)
4198 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
4201 static bool ScanDirForExecutable(SmallString<128> &Dir,
4202 ArrayRef<std::string> Names) {
4203 for (const auto &Name : Names) {
4204 llvm::sys::path::append(Dir, Name);
4205 if (llvm::sys::fs::can_execute(Twine(Dir)))
4207 llvm::sys::path::remove_filename(Dir);
4212 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
4213 SmallVector<std::string, 2> TargetSpecificExecutables;
4214 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4216 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4217 // attempting to use this prefix when looking for program paths.
4218 for (const auto &PrefixDir : PrefixDirs) {
4219 if (llvm::sys::fs::is_directory(PrefixDir)) {
4220 SmallString<128> P(PrefixDir);
4221 if (ScanDirForExecutable(P, TargetSpecificExecutables))
4224 SmallString<128> P((PrefixDir + Name).str());
4225 if (llvm::sys::fs::can_execute(Twine(P)))
4230 const ToolChain::path_list &List = TC.getProgramPaths();
4231 for (const auto &Path : List) {
4232 SmallString<128> P(Path);
4233 if (ScanDirForExecutable(P, TargetSpecificExecutables))
4237 // If all else failed, search the path.
4238 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4239 if (llvm::ErrorOr<std::string> P =
4240 llvm::sys::findProgramByName(TargetSpecificExecutable))
4246 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
4247 SmallString<128> Path;
4248 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
4250 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4257 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4258 SmallString<128> Output;
4259 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4260 // FIXME: If anybody needs it, implement this obscure rule:
4261 // "If you specify a directory without a file name, the default file name
4262 // is VCx0.pch., where x is the major version of Visual C++ in use."
4263 Output = FpArg->getValue();
4265 // "If you do not specify an extension as part of the path name, an
4266 // extension of .pch is assumed. "
4267 if (!llvm::sys::path::has_extension(Output))
4269 } else if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc)) {
4270 Output = YcArg->getValue();
4271 llvm::sys::path::replace_extension(Output, ".pch");
4274 llvm::sys::path::replace_extension(Output, ".pch");
4276 return Output.str();
4279 const ToolChain &Driver::getToolChain(const ArgList &Args,
4280 const llvm::Triple &Target) const {
4282 auto &TC = ToolChains[Target.str()];
4284 switch (Target.getOS()) {
4285 case llvm::Triple::Haiku:
4286 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
4288 case llvm::Triple::Ananas:
4289 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4291 case llvm::Triple::CloudABI:
4292 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
4294 case llvm::Triple::Darwin:
4295 case llvm::Triple::MacOSX:
4296 case llvm::Triple::IOS:
4297 case llvm::Triple::TvOS:
4298 case llvm::Triple::WatchOS:
4299 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
4301 case llvm::Triple::DragonFly:
4302 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
4304 case llvm::Triple::OpenBSD:
4305 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
4307 case llvm::Triple::NetBSD:
4308 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
4310 case llvm::Triple::FreeBSD:
4311 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
4313 case llvm::Triple::Minix:
4314 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
4316 case llvm::Triple::Linux:
4317 case llvm::Triple::ELFIAMCU:
4318 if (Target.getArch() == llvm::Triple::hexagon)
4319 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4321 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4322 !Target.hasEnvironment())
4323 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4326 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
4328 case llvm::Triple::NaCl:
4329 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
4331 case llvm::Triple::Fuchsia:
4332 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
4334 case llvm::Triple::Solaris:
4335 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
4337 case llvm::Triple::AMDHSA:
4338 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
4340 case llvm::Triple::Win32:
4341 switch (Target.getEnvironment()) {
4343 if (Target.isOSBinFormatELF())
4344 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4345 else if (Target.isOSBinFormatMachO())
4346 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
4348 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4350 case llvm::Triple::GNU:
4351 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
4353 case llvm::Triple::Itanium:
4354 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4357 case llvm::Triple::MSVC:
4358 case llvm::Triple::UnknownEnvironment:
4359 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4360 .startswith_lower("bfd"))
4361 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4362 *this, Target, Args);
4365 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
4369 case llvm::Triple::PS4:
4370 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
4372 case llvm::Triple::Contiki:
4373 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
4376 // Of these targets, Hexagon is the only one that might have
4377 // an OS of Linux, in which case it got handled above already.
4378 switch (Target.getArch()) {
4379 case llvm::Triple::tce:
4380 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
4382 case llvm::Triple::tcele:
4383 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
4385 case llvm::Triple::hexagon:
4386 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4389 case llvm::Triple::lanai:
4390 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
4392 case llvm::Triple::xcore:
4393 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
4395 case llvm::Triple::wasm32:
4396 case llvm::Triple::wasm64:
4397 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
4399 case llvm::Triple::avr:
4400 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
4403 if (Target.getVendor() == llvm::Triple::Myriad)
4404 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4406 else if (toolchains::BareMetal::handlesTarget(Target))
4407 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
4408 else if (Target.isOSBinFormatELF())
4409 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4410 else if (Target.isOSBinFormatMachO())
4411 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
4413 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4418 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4419 // compiles always need two toolchains, the CUDA toolchain and the host
4420 // toolchain. So the only valid way to create a CUDA toolchain is via
4421 // CreateOffloadingDeviceToolChains.
4426 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
4427 // Say "no" if there is not exactly one input of a type clang understands.
4428 if (JA.size() != 1 ||
4429 !types::isAcceptedByClang((*JA.input_begin())->getType()))
4432 // And say "no" if this is not a kind of action clang understands.
4433 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
4434 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
4440 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4441 /// grouped values as integers. Numbers which are not provided are set to 0.
4443 /// \return True if the entire string was parsed (9.2), or all groups were
4444 /// parsed (10.3.5extrastuff).
4445 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4446 unsigned &Micro, bool &HadExtra) {
4449 Major = Minor = Micro = 0;
4453 if (Str.consumeInteger(10, Major))
4460 Str = Str.drop_front(1);
4462 if (Str.consumeInteger(10, Minor))
4468 Str = Str.drop_front(1);
4470 if (Str.consumeInteger(10, Micro))
4477 /// Parse digits from a string \p Str and fulfill \p Digits with
4478 /// the parsed numbers. This method assumes that the max number of
4479 /// digits to look for is equal to Digits.size().
4481 /// \return True if the entire string was parsed and there are
4482 /// no extra characters remaining at the end.
4483 bool Driver::GetReleaseVersion(StringRef Str,
4484 MutableArrayRef<unsigned> Digits) {
4488 unsigned CurDigit = 0;
4489 while (CurDigit < Digits.size()) {
4491 if (Str.consumeInteger(10, Digit))
4493 Digits[CurDigit] = Digit;
4498 Str = Str.drop_front(1);
4502 // More digits than requested, bail out...
4506 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4507 unsigned IncludedFlagsBitmask = 0;
4508 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
4510 if (Mode == CLMode) {
4511 // Include CL and Core options.
4512 IncludedFlagsBitmask |= options::CLOption;
4513 IncludedFlagsBitmask |= options::CoreOption;
4515 ExcludedFlagsBitmask |= options::CLOption;
4518 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4521 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
4522 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);