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/Bitrig.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/BareMetal.h"
27 #include "ToolChains/Haiku.h"
28 #include "ToolChains/Hexagon.h"
29 #include "ToolChains/Lanai.h"
30 #include "ToolChains/Linux.h"
31 #include "ToolChains/MinGW.h"
32 #include "ToolChains/Minix.h"
33 #include "ToolChains/MipsLinux.h"
34 #include "ToolChains/MSVC.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/Option/Arg.h"
62 #include "llvm/Option/ArgList.h"
63 #include "llvm/Option/OptSpecifier.h"
64 #include "llvm/Option/OptTable.h"
65 #include "llvm/Option/Option.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/FileSystem.h"
68 #include "llvm/Support/Path.h"
69 #include "llvm/Support/PrettyStackTrace.h"
70 #include "llvm/Support/Process.h"
71 #include "llvm/Support/Program.h"
72 #include "llvm/Support/TargetRegistry.h"
73 #include "llvm/Support/raw_ostream.h"
78 #include <unistd.h> // getpid
81 using namespace clang::driver;
82 using namespace clang;
83 using namespace llvm::opt;
85 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
86 DiagnosticsEngine &Diags,
87 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
88 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
89 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
90 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
91 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
92 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
93 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
94 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
95 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
96 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
97 GenReproducer(false), SuppressMissingInputWarning(false) {
99 // Provide a sane fallback if no VFS is specified.
101 this->VFS = vfs::getRealFileSystem();
103 Name = llvm::sys::path::filename(ClangExecutable);
104 Dir = llvm::sys::path::parent_path(ClangExecutable);
105 InstalledDir = Dir; // Provide a sensible default installed dir.
107 // Compute the path to the resource directory.
108 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
109 SmallString<128> P(Dir);
110 if (ClangResourceDir != "") {
111 llvm::sys::path::append(P, ClangResourceDir);
113 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
114 P = llvm::sys::path::parent_path(Dir);
115 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
116 CLANG_VERSION_STRING);
118 ResourceDir = P.str();
121 void Driver::ParseDriverMode(StringRef ProgramName,
122 ArrayRef<const char *> Args) {
123 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
124 StringRef DefaultMode(Default.second);
125 setDriverModeFromOption(DefaultMode);
127 for (const char *ArgPtr : Args) {
128 // Ingore nullptrs, they are response file's EOL markers
129 if (ArgPtr == nullptr)
131 const StringRef Arg = ArgPtr;
132 setDriverModeFromOption(Arg);
136 void Driver::setDriverModeFromOption(StringRef Opt) {
137 const std::string OptName =
138 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
139 if (!Opt.startswith(OptName))
141 StringRef Value = Opt.drop_front(OptName.size());
143 const unsigned M = llvm::StringSwitch<unsigned>(Value)
144 .Case("gcc", GCCMode)
145 .Case("g++", GXXMode)
146 .Case("cpp", CPPMode)
151 Mode = static_cast<DriverMode>(M);
153 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
156 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
157 bool &ContainsError) {
158 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
159 ContainsError = false;
161 unsigned IncludedFlagsBitmask;
162 unsigned ExcludedFlagsBitmask;
163 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
164 getIncludeExcludeOptionFlagMasks();
166 unsigned MissingArgIndex, MissingArgCount;
168 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
169 IncludedFlagsBitmask, ExcludedFlagsBitmask);
171 // Check for missing argument error.
172 if (MissingArgCount) {
173 Diag(diag::err_drv_missing_argument)
174 << Args.getArgString(MissingArgIndex) << MissingArgCount;
176 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
177 SourceLocation()) > DiagnosticsEngine::Warning;
180 // Check for unsupported options.
181 for (const Arg *A : Args) {
182 if (A->getOption().hasFlag(options::Unsupported)) {
183 Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
184 ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt,
186 DiagnosticsEngine::Warning;
190 // Warn about -mcpu= without an argument.
191 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
192 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
193 ContainsError |= Diags.getDiagnosticLevel(
194 diag::warn_drv_empty_joined_argument,
195 SourceLocation()) > DiagnosticsEngine::Warning;
199 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
200 auto ID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
201 : diag::err_drv_unknown_argument;
203 Diags.Report(ID) << A->getAsString(Args);
204 ContainsError |= Diags.getDiagnosticLevel(ID, SourceLocation()) >
205 DiagnosticsEngine::Warning;
211 // Determine which compilation mode we are in. We look for options which
212 // affect the phase, starting with the earliest phases, and record which
213 // option we used to determine the final phase.
214 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
215 Arg **FinalPhaseArg) const {
216 Arg *PhaseArg = nullptr;
217 phases::ID FinalPhase;
219 // -{E,EP,P,M,MM} only run the preprocessor.
220 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
221 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
222 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
223 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
224 FinalPhase = phases::Preprocess;
226 // --precompile only runs up to precompilation.
227 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
228 FinalPhase = phases::Precompile;
230 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
231 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
232 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
233 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
234 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
235 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
236 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
237 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
238 options::OPT__analyze_auto)) ||
239 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
240 FinalPhase = phases::Compile;
242 // -S only runs up to the backend.
243 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
244 FinalPhase = phases::Backend;
246 // -c compilation only runs up to the assembler.
247 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
248 FinalPhase = phases::Assemble;
250 // Otherwise do everything.
252 FinalPhase = phases::Link;
255 *FinalPhaseArg = PhaseArg;
260 static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
262 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
263 Args.getBaseArgs().MakeIndex(Value), Value.data());
264 Args.AddSynthesizedArg(A);
269 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
270 DerivedArgList *DAL = new DerivedArgList(Args);
272 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
273 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
274 for (Arg *A : Args) {
275 // Unfortunately, we have to parse some forwarding options (-Xassembler,
276 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
277 // (assembler and preprocessor), or bypass a previous driver ('collect2').
279 // Rewrite linker options, to replace --no-demangle with a custom internal
281 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
282 A->getOption().matches(options::OPT_Xlinker)) &&
283 A->containsValue("--no-demangle")) {
284 // Add the rewritten no-demangle argument.
285 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
287 // Add the remaining values as Xlinker arguments.
288 for (StringRef Val : A->getValues())
289 if (Val != "--no-demangle")
290 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
295 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
296 // some build systems. We don't try to be complete here because we don't
297 // care to encourage this usage model.
298 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
299 (A->getValue(0) == StringRef("-MD") ||
300 A->getValue(0) == StringRef("-MMD"))) {
301 // Rewrite to -MD/-MMD along with -MF.
302 if (A->getValue(0) == StringRef("-MD"))
303 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
305 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
306 if (A->getNumValues() == 2)
307 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
312 // Rewrite reserved library names.
313 if (A->getOption().matches(options::OPT_l)) {
314 StringRef Value = A->getValue();
316 // Rewrite unless -nostdlib is present.
317 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
318 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
322 // Rewrite unconditionally.
323 if (Value == "cc_kext") {
324 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
329 // Pick up inputs via the -- option.
330 if (A->getOption().matches(options::OPT__DASH_DASH)) {
332 for (StringRef Val : A->getValues())
333 DAL->append(MakeInputArg(*DAL, *Opts, Val));
340 // Enforce -static if -miamcu is present.
341 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
342 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
344 // Add a default value of -mlinker-version=, if one was given and the user
345 // didn't specify one.
346 #if defined(HOST_LINK_VERSION)
347 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
348 strlen(HOST_LINK_VERSION) > 0) {
349 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
351 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
358 /// \brief Compute target triple from args.
360 /// This routine provides the logic to compute a target triple from various
361 /// args passed to the driver and the default triple string.
362 static llvm::Triple computeTargetTriple(const Driver &D,
363 StringRef DefaultTargetTriple,
365 StringRef DarwinArchName = "") {
366 // FIXME: Already done in Compilation *Driver::BuildCompilation
367 if (const Arg *A = Args.getLastArg(options::OPT_target))
368 DefaultTargetTriple = A->getValue();
370 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
372 // Handle Apple-specific options available here.
373 if (Target.isOSBinFormatMachO()) {
374 // If an explict Darwin arch name is given, that trumps all.
375 if (!DarwinArchName.empty()) {
376 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
380 // Handle the Darwin '-arch' flag.
381 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
382 StringRef ArchName = A->getValue();
383 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
387 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
388 // '-mbig-endian'/'-EB'.
389 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
390 options::OPT_mbig_endian)) {
391 if (A->getOption().matches(options::OPT_mlittle_endian)) {
392 llvm::Triple LE = Target.getLittleEndianArchVariant();
393 if (LE.getArch() != llvm::Triple::UnknownArch)
394 Target = std::move(LE);
396 llvm::Triple BE = Target.getBigEndianArchVariant();
397 if (BE.getArch() != llvm::Triple::UnknownArch)
398 Target = std::move(BE);
402 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
403 if (Target.getArch() == llvm::Triple::tce ||
404 Target.getOS() == llvm::Triple::Minix)
407 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
408 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
409 options::OPT_m32, options::OPT_m16);
411 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
413 if (A->getOption().matches(options::OPT_m64)) {
414 AT = Target.get64BitArchVariant().getArch();
415 if (Target.getEnvironment() == llvm::Triple::GNUX32)
416 Target.setEnvironment(llvm::Triple::GNU);
417 } else if (A->getOption().matches(options::OPT_mx32) &&
418 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
419 AT = llvm::Triple::x86_64;
420 Target.setEnvironment(llvm::Triple::GNUX32);
421 } else if (A->getOption().matches(options::OPT_m32)) {
422 AT = Target.get32BitArchVariant().getArch();
423 if (Target.getEnvironment() == llvm::Triple::GNUX32)
424 Target.setEnvironment(llvm::Triple::GNU);
425 } else if (A->getOption().matches(options::OPT_m16) &&
426 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
427 AT = llvm::Triple::x86;
428 Target.setEnvironment(llvm::Triple::CODE16);
431 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
435 // Handle -miamcu flag.
436 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
437 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
438 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
441 if (A && !A->getOption().matches(options::OPT_m32))
442 D.Diag(diag::err_drv_argument_not_allowed_with)
443 << "-miamcu" << A->getBaseArg().getAsString(Args);
445 Target.setArch(llvm::Triple::x86);
446 Target.setArchName("i586");
447 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
448 Target.setEnvironmentName("");
449 Target.setOS(llvm::Triple::ELFIAMCU);
450 Target.setVendor(llvm::Triple::UnknownVendor);
451 Target.setVendorName("intel");
457 // \brief Parse the LTO options and record the type of LTO compilation
458 // based on which -f(no-)?lto(=.*)? option occurs last.
459 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
461 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
462 options::OPT_fno_lto, false))
465 StringRef LTOName("full");
467 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
469 LTOName = A->getValue();
471 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
472 .Case("full", LTOK_Full)
473 .Case("thin", LTOK_Thin)
474 .Default(LTOK_Unknown);
476 if (LTOMode == LTOK_Unknown) {
478 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
483 /// Compute the desired OpenMP runtime from the flags provided.
484 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
485 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
487 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
489 RuntimeName = A->getValue();
491 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
492 .Case("libomp", OMPRT_OMP)
493 .Case("libgomp", OMPRT_GOMP)
494 .Case("libiomp5", OMPRT_IOMP5)
495 .Default(OMPRT_Unknown);
497 if (RT == OMPRT_Unknown) {
499 Diag(diag::err_drv_unsupported_option_argument)
500 << A->getOption().getName() << A->getValue();
502 // FIXME: We could use a nicer diagnostic here.
503 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
509 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
515 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
516 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
517 return types::isCuda(I.first);
519 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
520 const llvm::Triple &HostTriple = HostTC->getTriple();
521 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
522 : "nvptx-nvidia-cuda");
523 // Use the CUDA and host triples as the key into the ToolChains map, because
524 // the device toolchain we create depends on both.
525 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
527 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
528 *this, CudaTriple, *HostTC, C.getInputArgs());
530 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
536 // We need to generate an OpenMP toolchain if the user specified targets with
537 // the -fopenmp-targets option.
538 if (Arg *OpenMPTargets =
539 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
540 if (OpenMPTargets->getNumValues()) {
541 // We expect that -fopenmp-targets is always used in conjunction with the
542 // option -fopenmp specifying a valid runtime with offloading support,
543 // i.e. libomp or libiomp.
544 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
545 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
546 options::OPT_fno_openmp, false);
547 if (HasValidOpenMPRuntime) {
548 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
549 HasValidOpenMPRuntime =
550 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
553 if (HasValidOpenMPRuntime) {
554 llvm::StringMap<const char *> FoundNormalizedTriples;
555 for (const char *Val : OpenMPTargets->getValues()) {
556 llvm::Triple TT(Val);
557 std::string NormalizedName = TT.normalize();
559 // Make sure we don't have a duplicate triple.
560 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
561 if (Duplicate != FoundNormalizedTriples.end()) {
562 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
563 << Val << Duplicate->second;
567 // Store the current triple so that we can check for duplicates in the
568 // following iterations.
569 FoundNormalizedTriples[NormalizedName] = Val;
571 // If the specified target is invalid, emit a diagnostic.
572 if (TT.getArch() == llvm::Triple::UnknownArch)
573 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
576 // CUDA toolchains have to be selected differently. They pair host
577 // and device in their implementation.
579 const ToolChain *HostTC =
580 C.getSingleOffloadToolChain<Action::OFK_Host>();
581 assert(HostTC && "Host toolchain should be always defined.");
583 ToolChains[TT.str() + "/" + HostTC->getTriple().str()];
585 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
586 *this, TT, *HostTC, C.getInputArgs());
589 TC = &getToolChain(C.getInputArgs(), TT);
590 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
594 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
596 Diag(clang::diag::warn_drv_empty_joined_argument)
597 << OpenMPTargets->getAsString(C.getInputArgs());
601 // TODO: Add support for other offloading programming models here.
607 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
608 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
610 // FIXME: Handle environment options which affect driver behavior, somewhere
611 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
613 if (Optional<std::string> CompilerPathValue =
614 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
615 StringRef CompilerPath = *CompilerPathValue;
616 while (!CompilerPath.empty()) {
617 std::pair<StringRef, StringRef> Split =
618 CompilerPath.split(llvm::sys::EnvPathSeparator);
619 PrefixDirs.push_back(Split.first);
620 CompilerPath = Split.second;
624 // We look for the driver mode option early, because the mode can affect
625 // how other options are parsed.
626 ParseDriverMode(ClangExecutable, ArgList.slice(1));
628 // FIXME: What are we going to do with -V and -b?
630 // FIXME: This stuff needs to go into the Compilation, not the driver.
634 InputArgList Args = ParseArgStrings(ArgList.slice(1), ContainsError);
636 // Silence driver warnings if requested
637 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
639 // -no-canonical-prefixes is used very early in main.
640 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
643 Args.ClaimAllArgs(options::OPT_pipe);
645 // Extract -ccc args.
647 // FIXME: We need to figure out where this behavior should live. Most of it
648 // should be outside in the client; the parts that aren't should have proper
649 // options, either by introducing new ones or by overloading gcc ones like -V
651 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
652 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
653 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
654 CCCGenericGCCName = A->getValue();
656 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
657 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
658 options::OPT_fno_crash_diagnostics,
659 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
660 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
661 // and getToolChain is const.
663 // clang-cl targets MSVC-style Win32.
664 llvm::Triple T(DefaultTargetTriple);
665 T.setOS(llvm::Triple::Win32);
666 T.setVendor(llvm::Triple::PC);
667 T.setEnvironment(llvm::Triple::MSVC);
668 DefaultTargetTriple = T.str();
670 if (const Arg *A = Args.getLastArg(options::OPT_target))
671 DefaultTargetTriple = A->getValue();
672 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
673 Dir = InstalledDir = A->getValue();
674 for (const Arg *A : Args.filtered(options::OPT_B)) {
676 PrefixDirs.push_back(A->getValue(0));
678 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
679 SysRoot = A->getValue();
680 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
681 DyldPrefix = A->getValue();
682 if (Args.hasArg(options::OPT_nostdlib))
685 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
686 ResourceDir = A->getValue();
688 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
689 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
690 .Case("cwd", SaveTempsCwd)
691 .Case("obj", SaveTempsObj)
692 .Default(SaveTempsCwd);
697 // Process -fembed-bitcode= flags.
698 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
699 StringRef Name = A->getValue();
700 unsigned Model = llvm::StringSwitch<unsigned>(Name)
701 .Case("off", EmbedNone)
702 .Case("all", EmbedBitcode)
703 .Case("bitcode", EmbedBitcode)
704 .Case("marker", EmbedMarker)
707 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
710 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
713 std::unique_ptr<llvm::opt::InputArgList> UArgs =
714 llvm::make_unique<InputArgList>(std::move(Args));
716 // Perform the default argument translations.
717 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
719 // Owned by the host.
720 const ToolChain &TC = getToolChain(
721 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
723 // The compilation takes ownership of Args.
724 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
727 if (!HandleImmediateArgs(*C))
730 // Construct the list of inputs.
732 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
734 // Populate the tool chains for the offloading devices, if any.
735 CreateOffloadingDeviceToolChains(*C, Inputs);
737 // Construct the list of abstract actions to perform for this compilation. On
738 // MachO targets this uses the driver-driver and universal actions.
739 if (TC.getTriple().isOSBinFormatMachO())
740 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
742 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
744 if (CCCPrintPhases) {
754 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
755 llvm::opt::ArgStringList ASL;
756 for (const auto *A : Args)
757 A->render(Args, ASL);
759 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
760 if (I != ASL.begin())
762 Command::printArg(OS, *I, true);
767 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
768 SmallString<128> &CrashDiagDir) {
769 using namespace llvm::sys;
770 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
771 "Only knows about .crash files on Darwin");
773 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
774 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
775 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
776 path::home_directory(CrashDiagDir);
777 if (CrashDiagDir.startswith("/var/root"))
779 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
787 fs::file_status FileStatus;
788 TimePoint<> LastAccessTime;
789 SmallString<128> CrashFilePath;
790 // Lookup the .crash files and get the one generated by a subprocess spawned
791 // by this driver invocation.
792 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
793 File != FileEnd && !EC; File.increment(EC)) {
794 StringRef FileName = path::filename(File->path());
795 if (!FileName.startswith(Name))
797 if (fs::status(File->path(), FileStatus))
799 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
800 llvm::MemoryBuffer::getFile(File->path());
803 // The first line should start with "Process:", otherwise this isn't a real
805 StringRef Data = CrashFile.get()->getBuffer();
806 if (!Data.startswith("Process:"))
808 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
809 size_t ParentProcPos = Data.find("Parent Process:");
810 if (ParentProcPos == StringRef::npos)
812 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
813 if (LineEnd == StringRef::npos)
815 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
816 int OpenBracket = -1, CloseBracket = -1;
817 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
818 if (ParentProcess[i] == '[')
820 if (ParentProcess[i] == ']')
823 // Extract the parent process PID from the .crash file and check whether
824 // it matches this driver invocation pid.
826 if (OpenBracket < 0 || CloseBracket < 0 ||
827 ParentProcess.slice(OpenBracket + 1, CloseBracket)
828 .getAsInteger(10, CrashPID) || CrashPID != PID) {
832 // Found a .crash file matching the driver pid. To avoid getting an older
833 // and misleading crash file, continue looking for the most recent.
834 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
835 // multiple crashes poiting to the same parent process. Since the driver
836 // does not collect pid information for the dispatched invocation there's
837 // currently no way to distinguish among them.
838 const auto FileAccessTime = FileStatus.getLastModificationTime();
839 if (FileAccessTime > LastAccessTime) {
840 CrashFilePath.assign(File->path());
841 LastAccessTime = FileAccessTime;
845 // If found, copy it over to the location of other reproducer files.
846 if (!CrashFilePath.empty()) {
847 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
856 // When clang crashes, produce diagnostic information including the fully
857 // preprocessed source file(s). Request that the developer attach the
858 // diagnostic information to a bug report.
859 void Driver::generateCompilationDiagnostics(Compilation &C,
860 const Command &FailingCommand) {
861 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
864 // Don't try to generate diagnostics for link or dsymutil jobs.
865 if (FailingCommand.getCreator().isLinkJob() ||
866 FailingCommand.getCreator().isDsymutilJob())
869 // Print the version of the compiler.
870 PrintVersion(C, llvm::errs());
872 Diag(clang::diag::note_drv_command_failed_diag_msg)
873 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
874 "crash backtrace, preprocessed source, and associated run script.";
876 // Suppress driver output and emit preprocessor output to temp file.
878 CCGenDiagnostics = true;
880 // Save the original job command(s).
881 Command Cmd = FailingCommand;
883 // Keep track of whether we produce any errors while trying to produce
884 // preprocessed sources.
885 DiagnosticErrorTrap Trap(Diags);
887 // Suppress tool output.
888 C.initCompilationForDiagnostics();
890 // Construct the list of inputs.
892 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
894 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
895 bool IgnoreInput = false;
897 // Ignore input from stdin or any inputs that cannot be preprocessed.
898 // Check type first as not all linker inputs have a value.
899 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
901 } else if (!strcmp(it->second->getValue(), "-")) {
902 Diag(clang::diag::note_drv_command_failed_diag_msg)
903 << "Error generating preprocessed source(s) - "
904 "ignoring input from stdin.";
909 it = Inputs.erase(it);
916 if (Inputs.empty()) {
917 Diag(clang::diag::note_drv_command_failed_diag_msg)
918 << "Error generating preprocessed source(s) - "
919 "no preprocessable inputs.";
923 // Don't attempt to generate preprocessed files if multiple -arch options are
924 // used, unless they're all duplicates.
925 llvm::StringSet<> ArchNames;
926 for (const Arg *A : C.getArgs()) {
927 if (A->getOption().matches(options::OPT_arch)) {
928 StringRef ArchName = A->getValue();
929 ArchNames.insert(ArchName);
932 if (ArchNames.size() > 1) {
933 Diag(clang::diag::note_drv_command_failed_diag_msg)
934 << "Error generating preprocessed source(s) - cannot generate "
935 "preprocessed source with multiple -arch options.";
939 // Construct the list of abstract actions to perform for this compilation. On
940 // Darwin OSes this uses the driver-driver and builds universal actions.
941 const ToolChain &TC = C.getDefaultToolChain();
942 if (TC.getTriple().isOSBinFormatMachO())
943 BuildUniversalActions(C, TC, Inputs);
945 BuildActions(C, C.getArgs(), Inputs, C.getActions());
949 // If there were errors building the compilation, quit now.
950 if (Trap.hasErrorOccurred()) {
951 Diag(clang::diag::note_drv_command_failed_diag_msg)
952 << "Error generating preprocessed source(s).";
956 // Generate preprocessed output.
957 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
958 C.ExecuteJobs(C.getJobs(), FailingCommands);
960 // If any of the preprocessing commands failed, clean up and exit.
961 if (!FailingCommands.empty()) {
962 if (!isSaveTempsEnabled())
963 C.CleanupFileList(C.getTempFiles(), true);
965 Diag(clang::diag::note_drv_command_failed_diag_msg)
966 << "Error generating preprocessed source(s).";
970 const ArgStringList &TempFiles = C.getTempFiles();
971 if (TempFiles.empty()) {
972 Diag(clang::diag::note_drv_command_failed_diag_msg)
973 << "Error generating preprocessed source(s).";
977 Diag(clang::diag::note_drv_command_failed_diag_msg)
978 << "\n********************\n\n"
979 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
980 "Preprocessed source(s) and associated run script(s) are located at:";
982 SmallString<128> VFS;
983 SmallString<128> ReproCrashFilename;
984 for (const char *TempFile : TempFiles) {
985 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
986 if (ReproCrashFilename.empty()) {
987 ReproCrashFilename = TempFile;
988 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
990 if (StringRef(TempFile).endswith(".cache")) {
991 // In some cases (modules) we'll dump extra data to help with reproducing
992 // the crash into a directory next to the output.
993 VFS = llvm::sys::path::filename(TempFile);
994 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
998 // Assume associated files are based off of the first temporary file.
999 CrashReportInfo CrashInfo(TempFiles[0], VFS);
1001 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
1003 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
1005 Diag(clang::diag::note_drv_command_failed_diag_msg)
1006 << "Error generating run script: " + Script + " " + EC.message();
1008 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1009 << "# Driver args: ";
1010 printArgList(ScriptOS, C.getInputArgs());
1011 ScriptOS << "# Original command: ";
1012 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1013 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1014 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1017 // On darwin, provide information about the .crash diagnostic report.
1018 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1019 SmallString<128> CrashDiagDir;
1020 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1021 Diag(clang::diag::note_drv_command_failed_diag_msg)
1022 << ReproCrashFilename.str();
1023 } else { // Suggest a directory for the user to look for .crash files.
1024 llvm::sys::path::append(CrashDiagDir, Name);
1025 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1026 Diag(clang::diag::note_drv_command_failed_diag_msg)
1027 << "Crash backtrace is located in";
1028 Diag(clang::diag::note_drv_command_failed_diag_msg)
1029 << CrashDiagDir.str();
1030 Diag(clang::diag::note_drv_command_failed_diag_msg)
1031 << "(choose the .crash file that corresponds to your crash)";
1035 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1036 options::OPT_frewrite_map_file_EQ))
1037 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1039 Diag(clang::diag::note_drv_command_failed_diag_msg)
1040 << "\n\n********************";
1043 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1044 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
1045 // if the tool does not support response files, there is a chance/ that things
1046 // will just work without a response file, so we silently just skip it.
1047 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1048 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
1051 std::string TmpName = GetTemporaryPath("response", "txt");
1052 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1055 int Driver::ExecuteCompilation(
1057 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1058 // Just print if -### was present.
1059 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1060 C.getJobs().Print(llvm::errs(), "\n", true);
1064 // If there were errors building the compilation, quit now.
1065 if (Diags.hasErrorOccurred())
1068 // Set up response file names for each command, if necessary
1069 for (auto &Job : C.getJobs())
1070 setUpResponseFiles(C, Job);
1072 C.ExecuteJobs(C.getJobs(), FailingCommands);
1074 // Remove temp files.
1075 C.CleanupFileList(C.getTempFiles());
1077 // If the command succeeded, we are done.
1078 if (FailingCommands.empty())
1081 // Otherwise, remove result files and print extra information about abnormal
1083 for (const auto &CmdPair : FailingCommands) {
1084 int Res = CmdPair.first;
1085 const Command *FailingCommand = CmdPair.second;
1087 // Remove result files if we're not saving temps.
1088 if (!isSaveTempsEnabled()) {
1089 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1090 C.CleanupFileMap(C.getResultFiles(), JA, true);
1092 // Failure result files are valid unless we crashed.
1094 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1097 // Print extra information about abnormal failures, if possible.
1099 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1100 // status was 1, assume the command failed normally. In particular, if it
1101 // was the compiler then assume it gave a reasonable error code. Failures
1102 // in other tools are less common, and they generally have worse
1103 // diagnostics, so always print the diagnostic there.
1104 const Tool &FailingTool = FailingCommand->getCreator();
1106 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1107 // FIXME: See FIXME above regarding result code interpretation.
1109 Diag(clang::diag::err_drv_command_signalled)
1110 << FailingTool.getShortName();
1112 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1119 void Driver::PrintHelp(bool ShowHidden) const {
1120 unsigned IncludedFlagsBitmask;
1121 unsigned ExcludedFlagsBitmask;
1122 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1123 getIncludeExcludeOptionFlagMasks();
1125 ExcludedFlagsBitmask |= options::NoDriverOption;
1127 ExcludedFlagsBitmask |= HelpHidden;
1129 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1130 IncludedFlagsBitmask, ExcludedFlagsBitmask);
1133 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1134 // FIXME: The following handlers should use a callback mechanism, we don't
1135 // know what the client would like to do.
1136 OS << getClangFullVersion() << '\n';
1137 const ToolChain &TC = C.getDefaultToolChain();
1138 OS << "Target: " << TC.getTripleString() << '\n';
1140 // Print the threading model.
1141 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1142 // Don't print if the ToolChain would have barfed on it already
1143 if (TC.isThreadModelSupported(A->getValue()))
1144 OS << "Thread model: " << A->getValue();
1146 OS << "Thread model: " << TC.getThreadModel();
1149 // Print out the install directory.
1150 OS << "InstalledDir: " << InstalledDir << '\n';
1153 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1155 static void PrintDiagnosticCategories(raw_ostream &OS) {
1156 // Skip the empty category.
1157 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1159 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1162 bool Driver::HandleImmediateArgs(const Compilation &C) {
1163 // The order these options are handled in gcc is all over the place, but we
1164 // don't expect inconsistencies w.r.t. that to matter in practice.
1166 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1167 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1171 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1172 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1173 // return an answer which matches our definition of __VERSION__.
1175 // If we want to return a more correct answer some day, then we should
1176 // introduce a non-pedantically GCC compatible mode to Clang in which we
1177 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1178 llvm::outs() << "4.2.1\n";
1182 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1183 PrintDiagnosticCategories(llvm::outs());
1187 if (C.getArgs().hasArg(options::OPT_help) ||
1188 C.getArgs().hasArg(options::OPT__help_hidden)) {
1189 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1193 if (C.getArgs().hasArg(options::OPT__version)) {
1194 // Follow gcc behavior and use stdout for --version and stderr for -v.
1195 PrintVersion(C, llvm::outs());
1197 // Print registered targets.
1198 llvm::outs() << '\n';
1199 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
1203 if (C.getArgs().hasArg(options::OPT_v) ||
1204 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1205 PrintVersion(C, llvm::errs());
1206 SuppressMissingInputWarning = true;
1209 const ToolChain &TC = C.getDefaultToolChain();
1211 if (C.getArgs().hasArg(options::OPT_v))
1212 TC.printVerboseInfo(llvm::errs());
1214 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1215 llvm::outs() << ResourceDir << '\n';
1219 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1220 llvm::outs() << "programs: =";
1221 bool separator = false;
1222 for (const std::string &Path : TC.getProgramPaths()) {
1224 llvm::outs() << ':';
1225 llvm::outs() << Path;
1228 llvm::outs() << "\n";
1229 llvm::outs() << "libraries: =" << ResourceDir;
1231 StringRef sysroot = C.getSysRoot();
1233 for (const std::string &Path : TC.getFilePaths()) {
1234 // Always print a separator. ResourceDir was the first item shown.
1235 llvm::outs() << ':';
1236 // Interpretation of leading '=' is needed only for NetBSD.
1238 llvm::outs() << sysroot << Path.substr(1);
1240 llvm::outs() << Path;
1242 llvm::outs() << "\n";
1246 // FIXME: The following handlers should use a callback mechanism, we don't
1247 // know what the client would like to do.
1248 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1249 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1253 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1254 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
1258 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1259 // Print out all options that start with a given argument. This is used for
1260 // shell autocompletion.
1261 StringRef PassedFlags = A->getValue();
1262 std::vector<std::string> SuggestedCompletions;
1264 unsigned short DisableFlags = options::NoDriverOption | options::Unsupported | options::Ignored;
1265 // We want to show cc1-only options only when clang is invoked as "clang -cc1".
1266 // When clang is invoked as "clang -cc1", we add "#" to the beginning of an --autocomplete
1267 // option so that the clang driver can distinguish whether it is requested to show cc1-only options or not.
1268 if (PassedFlags[0] == '#') {
1269 DisableFlags &= ~options::NoDriverOption;
1270 PassedFlags = PassedFlags.substr(1);
1273 if (PassedFlags.find(',') == StringRef::npos) {
1274 // If the flag is in the form of "--autocomplete=-foo",
1275 // we were requested to print out all option names that start with "-foo".
1276 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1277 SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
1279 // We have to query the -W flags manually as they're not in the OptTable.
1280 // TODO: Find a good way to add them to OptTable instead and them remove
1282 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1283 if (S.startswith(PassedFlags))
1284 SuggestedCompletions.push_back(S);
1286 // If the flag is in the form of "--autocomplete=foo,bar", we were
1287 // requested to print out all option values for "-foo" that start with
1288 // "bar". For example,
1289 // "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
1290 StringRef Option, Arg;
1291 std::tie(Option, Arg) = PassedFlags.split(',');
1292 SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
1295 // Sort the autocomplete candidates so that shells print them out in a
1296 // deterministic order. We could sort in any way, but we chose
1297 // case-insensitive sorting for consistency with the -help option
1298 // which prints out options in the case-insensitive alphabetical order.
1299 std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
1300 [](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
1302 llvm::outs() << llvm::join(SuggestedCompletions, " ") << '\n';
1306 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1307 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1309 case ToolChain::RLT_CompilerRT:
1310 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1312 case ToolChain::RLT_Libgcc:
1313 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1319 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1320 for (const Multilib &Multilib : TC.getMultilibs())
1321 llvm::outs() << Multilib << "\n";
1325 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1326 for (const Multilib &Multilib : TC.getMultilibs()) {
1327 if (Multilib.gccSuffix().empty())
1328 llvm::outs() << ".\n";
1330 StringRef Suffix(Multilib.gccSuffix());
1331 assert(Suffix.front() == '/');
1332 llvm::outs() << Suffix.substr(1) << "\n";
1340 // Display an action graph human-readably. Action A is the "sink" node
1341 // and latest-occuring action. Traversal is in pre-order, visiting the
1342 // inputs to each action before printing the action itself.
1343 static unsigned PrintActions1(const Compilation &C, Action *A,
1344 std::map<Action *, unsigned> &Ids) {
1345 if (Ids.count(A)) // A was already visited.
1349 llvm::raw_string_ostream os(str);
1351 os << Action::getClassName(A->getKind()) << ", ";
1352 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1353 os << "\"" << IA->getInputArg().getValue() << "\"";
1354 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1355 os << '"' << BIA->getArchName() << '"' << ", {"
1356 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1357 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1358 bool IsFirst = true;
1359 OA->doOnEachDependence(
1360 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1361 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1362 // sm_35 this will generate:
1363 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1364 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1369 os << A->getOffloadingKindPrefix();
1373 os << TC->getTriple().normalize();
1376 os << ":" << BoundArch;
1379 os << " {" << PrintActions1(C, A, Ids) << "}";
1383 const ActionList *AL = &A->getInputs();
1386 const char *Prefix = "{";
1387 for (Action *PreRequisite : *AL) {
1388 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1396 // Append offload info for all options other than the offloading action
1397 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1398 std::string offload_str;
1399 llvm::raw_string_ostream offload_os(offload_str);
1400 if (!isa<OffloadAction>(A)) {
1401 auto S = A->getOffloadingKindPrefix();
1403 offload_os << ", (" << S;
1404 if (A->getOffloadingArch())
1405 offload_os << ", " << A->getOffloadingArch();
1410 unsigned Id = Ids.size();
1412 llvm::errs() << Id << ": " << os.str() << ", "
1413 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1418 // Print the action graphs in a compilation C.
1419 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1420 void Driver::PrintActions(const Compilation &C) const {
1421 std::map<Action *, unsigned> Ids;
1422 for (Action *A : C.getActions())
1423 PrintActions1(C, A, Ids);
1426 /// \brief Check whether the given input tree contains any compilation or
1427 /// assembly actions.
1428 static bool ContainsCompileOrAssembleAction(const Action *A) {
1429 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1430 isa<AssembleJobAction>(A))
1433 for (const Action *Input : A->inputs())
1434 if (ContainsCompileOrAssembleAction(Input))
1440 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1441 const InputList &BAInputs) const {
1442 DerivedArgList &Args = C.getArgs();
1443 ActionList &Actions = C.getActions();
1444 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1445 // Collect the list of architectures. Duplicates are allowed, but should only
1446 // be handled once (in the order seen).
1447 llvm::StringSet<> ArchNames;
1448 SmallVector<const char *, 4> Archs;
1449 for (Arg *A : Args) {
1450 if (A->getOption().matches(options::OPT_arch)) {
1451 // Validate the option here; we don't save the type here because its
1452 // particular spelling may participate in other driver choices.
1453 llvm::Triple::ArchType Arch =
1454 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1455 if (Arch == llvm::Triple::UnknownArch) {
1456 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1461 if (ArchNames.insert(A->getValue()).second)
1462 Archs.push_back(A->getValue());
1466 // When there is no explicit arch for this platform, make sure we still bind
1467 // the architecture (to the default) so that -Xarch_ is handled correctly.
1469 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1471 ActionList SingleActions;
1472 BuildActions(C, Args, BAInputs, SingleActions);
1474 // Add in arch bindings for every top level action, as well as lipo and
1475 // dsymutil steps if needed.
1476 for (Action* Act : SingleActions) {
1477 // Make sure we can lipo this kind of output. If not (and it is an actual
1478 // output) then we disallow, since we can't create an output file with the
1479 // right name without overwriting it. We could remove this oddity by just
1480 // changing the output names to include the arch, which would also fix
1481 // -save-temps. Compatibility wins for now.
1483 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1484 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1485 << types::getTypeName(Act->getType());
1488 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1489 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1491 // Lipo if necessary, we do it this way because we need to set the arch flag
1492 // so that -Xarch_ gets overwritten.
1493 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1494 Actions.append(Inputs.begin(), Inputs.end());
1496 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1498 // Handle debug info queries.
1499 Arg *A = Args.getLastArg(options::OPT_g_Group);
1500 if (A && !A->getOption().matches(options::OPT_g0) &&
1501 !A->getOption().matches(options::OPT_gstabs) &&
1502 ContainsCompileOrAssembleAction(Actions.back())) {
1504 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1505 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1506 // because the debug info will refer to a temporary object file which
1507 // will be removed at the end of the compilation process.
1508 if (Act->getType() == types::TY_Image) {
1510 Inputs.push_back(Actions.back());
1513 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1516 // Verify the debug info output.
1517 if (Args.hasArg(options::OPT_verify_debug_info)) {
1518 Action* LastAction = Actions.back();
1520 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1521 LastAction, types::TY_Nothing));
1527 /// \brief Check that the file referenced by Value exists. If it doesn't,
1528 /// issue a diagnostic and return false.
1529 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1530 StringRef Value, types::ID Ty) {
1531 if (!D.getCheckInputsExist())
1534 // stdin always exists.
1538 SmallString<64> Path(Value);
1539 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1540 if (!llvm::sys::path::is_absolute(Path)) {
1541 SmallString<64> Directory(WorkDir->getValue());
1542 llvm::sys::path::append(Directory, Value);
1543 Path.assign(Directory);
1547 if (llvm::sys::fs::exists(Twine(Path)))
1551 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1552 llvm::sys::Process::FindInEnvPath("LIB", Value))
1555 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1556 // Arguments to the /link flag might cause the linker to search for object
1557 // and library files in paths we don't know about. Don't error in such
1563 D.Diag(clang::diag::err_drv_no_such_file) << Path;
1567 // Construct a the list of inputs and their types.
1568 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1569 InputList &Inputs) const {
1570 // Track the current user specified (-x) input. We also explicitly track the
1571 // argument used to set the type; we only want to claim the type when we
1572 // actually use it, so we warn about unused -x arguments.
1573 types::ID InputType = types::TY_Nothing;
1574 Arg *InputTypeArg = nullptr;
1576 // The last /TC or /TP option sets the input type to C or C++ globally.
1577 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1578 options::OPT__SLASH_TP)) {
1579 InputTypeArg = TCTP;
1580 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1584 Arg *Previous = nullptr;
1585 bool ShowNote = false;
1586 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1588 Diag(clang::diag::warn_drv_overriding_flag_option)
1589 << Previous->getSpelling() << A->getSpelling();
1595 Diag(clang::diag::note_drv_t_option_is_global);
1597 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1598 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1601 for (Arg *A : Args) {
1602 if (A->getOption().getKind() == Option::InputClass) {
1603 const char *Value = A->getValue();
1604 types::ID Ty = types::TY_INVALID;
1606 // Infer the input type if necessary.
1607 if (InputType == types::TY_Nothing) {
1608 // If there was an explicit arg for this, claim it.
1610 InputTypeArg->claim();
1612 // stdin must be handled specially.
1613 if (memcmp(Value, "-", 2) == 0) {
1614 // If running with -E, treat as a C input (this changes the builtin
1615 // macros, for example). This may be overridden by -ObjC below.
1617 // Otherwise emit an error but still use a valid type to avoid
1618 // spurious errors (e.g., no inputs).
1619 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1620 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1621 : clang::diag::err_drv_unknown_stdin_type);
1624 // Otherwise lookup by extension.
1625 // Fallback is C if invoked as C preprocessor or Object otherwise.
1626 // We use a host hook here because Darwin at least has its own
1627 // idea of what .s is.
1628 if (const char *Ext = strrchr(Value, '.'))
1629 Ty = TC.LookupTypeForExtension(Ext + 1);
1631 if (Ty == types::TY_INVALID) {
1635 Ty = types::TY_Object;
1638 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1639 // should autodetect some input files as C++ for g++ compatibility.
1641 types::ID OldTy = Ty;
1642 Ty = types::lookupCXXTypeForCType(Ty);
1645 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1646 << getTypeName(OldTy) << getTypeName(Ty);
1650 // -ObjC and -ObjC++ override the default language, but only for "source
1651 // files". We just treat everything that isn't a linker input as a
1654 // FIXME: Clean this up if we move the phase sequence into the type.
1655 if (Ty != types::TY_Object) {
1656 if (Args.hasArg(options::OPT_ObjC))
1657 Ty = types::TY_ObjC;
1658 else if (Args.hasArg(options::OPT_ObjCXX))
1659 Ty = types::TY_ObjCXX;
1662 assert(InputTypeArg && "InputType set w/o InputTypeArg");
1663 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1664 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1666 const char *Ext = strrchr(Value, '.');
1667 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1668 Ty = types::TY_Object;
1670 if (Ty == types::TY_INVALID) {
1672 InputTypeArg->claim();
1676 if (DiagnoseInputExistence(*this, Args, Value, Ty))
1677 Inputs.push_back(std::make_pair(Ty, A));
1679 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1680 StringRef Value = A->getValue();
1681 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1682 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1683 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1686 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1687 StringRef Value = A->getValue();
1688 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1689 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1690 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1693 } else if (A->getOption().hasFlag(options::LinkerInput)) {
1694 // Just treat as object type, we could make a special type for this if
1696 Inputs.push_back(std::make_pair(types::TY_Object, A));
1698 } else if (A->getOption().matches(options::OPT_x)) {
1700 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1703 // Follow gcc behavior and treat as linker input for invalid -x
1704 // options. Its not clear why we shouldn't just revert to unknown; but
1705 // this isn't very important, we might as well be bug compatible.
1707 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1708 InputType = types::TY_Object;
1710 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1711 assert(A->getNumValues() == 1 && "The /U option has one value.");
1712 StringRef Val = A->getValue(0);
1713 if (Val.find_first_of("/\\") != StringRef::npos) {
1714 // Warn about e.g. "/Users/me/myfile.c".
1715 Diag(diag::warn_slash_u_filename) << Val;
1716 Diag(diag::note_use_dashdash);
1720 if (CCCIsCPP() && Inputs.empty()) {
1721 // If called as standalone preprocessor, stdin is processed
1722 // if no other input is present.
1723 Arg *A = MakeInputArg(Args, *Opts, "-");
1724 Inputs.push_back(std::make_pair(types::TY_C, A));
1729 /// Provides a convenient interface for different programming models to generate
1730 /// the required device actions.
1731 class OffloadingActionBuilder final {
1732 /// Flag used to trace errors in the builder.
1733 bool IsValid = false;
1735 /// The compilation that is using this builder.
1738 /// Map between an input argument and the offload kinds used to process it.
1739 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1741 /// Builder interface. It doesn't build anything or keep any state.
1742 class DeviceActionBuilder {
1744 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1746 enum ActionBuilderReturnCode {
1747 // The builder acted successfully on the current action.
1749 // The builder didn't have to act on the current action.
1751 // The builder was successful and requested the host action to not be
1757 /// Compilation associated with this builder.
1760 /// Tool chains associated with this builder. The same programming
1761 /// model may have associated one or more tool chains.
1762 SmallVector<const ToolChain *, 2> ToolChains;
1764 /// The derived arguments associated with this builder.
1765 DerivedArgList &Args;
1767 /// The inputs associated with this builder.
1768 const Driver::InputList &Inputs;
1770 /// The associated offload kind.
1771 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1774 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1775 const Driver::InputList &Inputs,
1776 Action::OffloadKind AssociatedOffloadKind)
1777 : C(C), Args(Args), Inputs(Inputs),
1778 AssociatedOffloadKind(AssociatedOffloadKind) {}
1779 virtual ~DeviceActionBuilder() {}
1781 /// Fill up the array \a DA with all the device dependences that should be
1782 /// added to the provided host action \a HostAction. By default it is
1784 virtual ActionBuilderReturnCode
1785 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1786 phases::ID CurPhase, phases::ID FinalPhase,
1788 return ABRT_Inactive;
1791 /// Update the state to include the provided host action \a HostAction as a
1792 /// dependency of the current device action. By default it is inactive.
1793 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1794 return ABRT_Inactive;
1797 /// Append top level actions generated by the builder. Return true if errors
1799 virtual void appendTopLevelActions(ActionList &AL) {}
1801 /// Append linker actions generated by the builder. Return true if errors
1803 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1805 /// Initialize the builder. Return true if any initialization errors are
1807 virtual bool initialize() { return false; }
1809 /// Return true if the builder can use bundling/unbundling.
1810 virtual bool canUseBundlerUnbundler() const { return false; }
1812 /// Return true if this builder is valid. We have a valid builder if we have
1813 /// associated device tool chains.
1814 bool isValid() { return !ToolChains.empty(); }
1816 /// Return the associated offload kind.
1817 Action::OffloadKind getAssociatedOffloadKind() {
1818 return AssociatedOffloadKind;
1822 /// \brief CUDA action builder. It injects device code in the host backend
1824 class CudaActionBuilder final : public DeviceActionBuilder {
1825 /// Flags to signal if the user requested host-only or device-only
1827 bool CompileHostOnly = false;
1828 bool CompileDeviceOnly = false;
1830 /// List of GPU architectures to use in this compilation.
1831 SmallVector<CudaArch, 4> GpuArchList;
1833 /// The CUDA actions for the current input.
1834 ActionList CudaDeviceActions;
1836 /// The CUDA fat binary if it was generated for the current input.
1837 Action *CudaFatBinary = nullptr;
1839 /// Flag that is set to true if this builder acted on the current input.
1840 bool IsActive = false;
1843 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1844 const Driver::InputList &Inputs)
1845 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1847 ActionBuilderReturnCode
1848 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1849 phases::ID CurPhase, phases::ID FinalPhase,
1850 PhasesTy &Phases) override {
1852 return ABRT_Inactive;
1854 // If we don't have more CUDA actions, we don't have any dependences to
1855 // create for the host.
1856 if (CudaDeviceActions.empty())
1857 return ABRT_Success;
1859 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1860 "Expecting one action per GPU architecture.");
1861 assert(!CompileHostOnly &&
1862 "Not expecting CUDA actions in host-only compilation.");
1864 // If we are generating code for the device or we are in a backend phase,
1865 // we attempt to generate the fat binary. We compile each arch to ptx and
1866 // assemble to cubin, then feed the cubin *and* the ptx into a device
1867 // "link" action, which uses fatbinary to combine these cubins into one
1868 // fatbin. The fatbin is then an input to the host action if not in
1869 // device-only mode.
1870 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1871 ActionList DeviceActions;
1872 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1873 // Produce the device action from the current phase up to the assemble
1875 for (auto Ph : Phases) {
1876 // Skip the phases that were already dealt with.
1879 // We have to be consistent with the host final phase.
1880 if (Ph > FinalPhase)
1883 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1884 C, Args, Ph, CudaDeviceActions[I]);
1886 if (Ph == phases::Assemble)
1890 // If we didn't reach the assemble phase, we can't generate the fat
1891 // binary. We don't need to generate the fat binary if we are not in
1892 // device-only mode.
1893 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1897 Action *AssembleAction = CudaDeviceActions[I];
1898 assert(AssembleAction->getType() == types::TY_Object);
1899 assert(AssembleAction->getInputs().size() == 1);
1901 Action *BackendAction = AssembleAction->getInputs()[0];
1902 assert(BackendAction->getType() == types::TY_PP_Asm);
1904 for (auto &A : {AssembleAction, BackendAction}) {
1905 OffloadAction::DeviceDependences DDep;
1906 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1908 DeviceActions.push_back(
1909 C.MakeAction<OffloadAction>(DDep, A->getType()));
1913 // We generate the fat binary if we have device input actions.
1914 if (!DeviceActions.empty()) {
1916 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1918 if (!CompileDeviceOnly) {
1919 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1921 // Clear the fat binary, it is already a dependence to an host
1923 CudaFatBinary = nullptr;
1926 // Remove the CUDA actions as they are already connected to an host
1927 // action or fat binary.
1928 CudaDeviceActions.clear();
1931 // We avoid creating host action in device-only mode.
1932 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
1933 } else if (CurPhase > phases::Backend) {
1934 // If we are past the backend phase and still have a device action, we
1935 // don't have to do anything as this action is already a device
1936 // top-level action.
1937 return ABRT_Success;
1940 assert(CurPhase < phases::Backend && "Generating single CUDA "
1941 "instructions should only occur "
1942 "before the backend phase!");
1944 // By default, we produce an action for each device arch.
1945 for (Action *&A : CudaDeviceActions)
1946 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1948 return ABRT_Success;
1951 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1952 // While generating code for CUDA, we only depend on the host input action
1953 // to trigger the creation of all the CUDA device actions.
1955 // If we are dealing with an input action, replicate it for each GPU
1956 // architecture. If we are in host-only mode we return 'success' so that
1957 // the host uses the CUDA offload kind.
1958 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1959 assert(!GpuArchList.empty() &&
1960 "We should have at least one GPU architecture.");
1962 // If the host input is not CUDA, we don't need to bother about this
1964 if (IA->getType() != types::TY_CUDA) {
1965 // The builder will ignore this input.
1967 return ABRT_Inactive;
1970 // Set the flag to true, so that the builder acts on the current input.
1973 if (CompileHostOnly)
1974 return ABRT_Success;
1976 // Replicate inputs for each GPU architecture.
1977 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1978 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1979 IA->getInputArg(), types::TY_CUDA_DEVICE));
1981 return ABRT_Success;
1984 return IsActive ? ABRT_Success : ABRT_Inactive;
1987 void appendTopLevelActions(ActionList &AL) override {
1988 // Utility to append actions to the top level list.
1989 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1990 OffloadAction::DeviceDependences Dep;
1991 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1993 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1996 // If we have a fat binary, add it to the list.
1997 if (CudaFatBinary) {
1998 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1999 CudaDeviceActions.clear();
2000 CudaFatBinary = nullptr;
2004 if (CudaDeviceActions.empty())
2007 // If we have CUDA actions at this point, that's because we have a have
2008 // partial compilation, so we should have an action for each GPU
2010 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2011 "Expecting one action per GPU architecture.");
2012 assert(ToolChains.size() == 1 &&
2013 "Expecting to have a sing CUDA toolchain.");
2014 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2015 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2017 CudaDeviceActions.clear();
2020 bool initialize() override {
2021 // We don't need to support CUDA.
2022 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
2025 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2026 assert(HostTC && "No toolchain for host compilation.");
2027 if (HostTC->getTriple().isNVPTX()) {
2028 // We do not support targeting NVPTX for host compilation. Throw
2029 // an error and abort pipeline construction early so we don't trip
2030 // asserts that assume device-side compilation.
2031 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
2035 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
2037 Arg *PartialCompilationArg = Args.getLastArg(
2038 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2039 options::OPT_cuda_compile_host_device);
2040 CompileHostOnly = PartialCompilationArg &&
2041 PartialCompilationArg->getOption().matches(
2042 options::OPT_cuda_host_only);
2043 CompileDeviceOnly = PartialCompilationArg &&
2044 PartialCompilationArg->getOption().matches(
2045 options::OPT_cuda_device_only);
2047 // Collect all cuda_gpu_arch parameters, removing duplicates.
2048 std::set<CudaArch> GpuArchs;
2050 for (Arg *A : Args) {
2051 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2052 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2056 const StringRef ArchStr = A->getValue();
2057 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2062 CudaArch Arch = StringToCudaArch(ArchStr);
2063 if (Arch == CudaArch::UNKNOWN) {
2064 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2066 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2067 GpuArchs.insert(Arch);
2068 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2069 GpuArchs.erase(Arch);
2071 llvm_unreachable("Unexpected option.");
2074 // Collect list of GPUs remaining in the set.
2075 for (CudaArch Arch : GpuArchs)
2076 GpuArchList.push_back(Arch);
2078 // Default to sm_20 which is the lowest common denominator for
2079 // supported GPUs. sm_20 code should work correctly, if
2080 // suboptimally, on all newer GPUs.
2081 if (GpuArchList.empty())
2082 GpuArchList.push_back(CudaArch::SM_20);
2088 /// OpenMP action builder. The host bitcode is passed to the device frontend
2089 /// and all the device linked images are passed to the host link phase.
2090 class OpenMPActionBuilder final : public DeviceActionBuilder {
2091 /// The OpenMP actions for the current input.
2092 ActionList OpenMPDeviceActions;
2094 /// The linker inputs obtained for each toolchain.
2095 SmallVector<ActionList, 8> DeviceLinkerInputs;
2098 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2099 const Driver::InputList &Inputs)
2100 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2102 ActionBuilderReturnCode
2103 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2104 phases::ID CurPhase, phases::ID FinalPhase,
2105 PhasesTy &Phases) override {
2107 // We should always have an action for each input.
2108 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2109 "Number of OpenMP actions and toolchains do not match.");
2111 // The host only depends on device action in the linking phase, when all
2112 // the device images have to be embedded in the host image.
2113 if (CurPhase == phases::Link) {
2114 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2115 "Toolchains and linker inputs sizes do not match.");
2116 auto LI = DeviceLinkerInputs.begin();
2117 for (auto *A : OpenMPDeviceActions) {
2122 // We passed the device action as a host dependence, so we don't need to
2123 // do anything else with them.
2124 OpenMPDeviceActions.clear();
2125 return ABRT_Success;
2128 // By default, we produce an action for each device arch.
2129 for (Action *&A : OpenMPDeviceActions)
2130 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2132 return ABRT_Success;
2135 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2137 // If this is an input action replicate it for each OpenMP toolchain.
2138 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2139 OpenMPDeviceActions.clear();
2140 for (unsigned I = 0; I < ToolChains.size(); ++I)
2141 OpenMPDeviceActions.push_back(
2142 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2143 return ABRT_Success;
2146 // If this is an unbundling action use it as is for each OpenMP toolchain.
2147 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2148 OpenMPDeviceActions.clear();
2149 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2150 OpenMPDeviceActions.push_back(UA);
2151 UA->registerDependentActionInfo(
2152 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2154 return ABRT_Success;
2157 // When generating code for OpenMP we use the host compile phase result as
2158 // a dependence to the device compile phase so that it can learn what
2159 // declarations should be emitted. However, this is not the only use for
2160 // the host action, so we prevent it from being collapsed.
2161 if (isa<CompileJobAction>(HostAction)) {
2162 HostAction->setCannotBeCollapsedWithNextDependentAction();
2163 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2164 "Toolchains and device action sizes do not match.");
2165 OffloadAction::HostDependence HDep(
2166 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2167 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2168 auto TC = ToolChains.begin();
2169 for (Action *&A : OpenMPDeviceActions) {
2170 assert(isa<CompileJobAction>(A));
2171 OffloadAction::DeviceDependences DDep;
2172 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2173 A = C.MakeAction<OffloadAction>(HDep, DDep);
2177 return ABRT_Success;
2180 void appendTopLevelActions(ActionList &AL) override {
2181 if (OpenMPDeviceActions.empty())
2184 // We should always have an action for each input.
2185 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2186 "Number of OpenMP actions and toolchains do not match.");
2188 // Append all device actions followed by the proper offload action.
2189 auto TI = ToolChains.begin();
2190 for (auto *A : OpenMPDeviceActions) {
2191 OffloadAction::DeviceDependences Dep;
2192 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2193 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2196 // We no longer need the action stored in this builder.
2197 OpenMPDeviceActions.clear();
2200 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2201 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2202 "Toolchains and linker inputs sizes do not match.");
2204 // Append a new link action for each device.
2205 auto TC = ToolChains.begin();
2206 for (auto &LI : DeviceLinkerInputs) {
2207 auto *DeviceLinkAction =
2208 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2209 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2210 Action::OFK_OpenMP);
2215 bool initialize() override {
2216 // Get the OpenMP toolchains. If we don't get any, the action builder will
2217 // know there is nothing to do related to OpenMP offloading.
2218 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2219 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2221 ToolChains.push_back(TI->second);
2223 DeviceLinkerInputs.resize(ToolChains.size());
2227 bool canUseBundlerUnbundler() const override {
2228 // OpenMP should use bundled files whenever possible.
2234 /// TODO: Add the implementation for other specialized builders here.
2237 /// Specialized builders being used by this offloading action builder.
2238 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2240 /// Flag set to true if all valid builders allow file bundling/unbundling.
2244 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2245 const Driver::InputList &Inputs)
2247 // Create a specialized builder for each device toolchain.
2251 // Create a specialized builder for CUDA.
2252 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2254 // Create a specialized builder for OpenMP.
2255 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2258 // TODO: Build other specialized builders here.
2261 // Initialize all the builders, keeping track of errors. If all valid
2262 // builders agree that we can use bundling, set the flag to true.
2263 unsigned ValidBuilders = 0u;
2264 unsigned ValidBuildersSupportingBundling = 0u;
2265 for (auto *SB : SpecializedBuilders) {
2266 IsValid = IsValid && !SB->initialize();
2268 // Update the counters if the builder is valid.
2269 if (SB->isValid()) {
2271 if (SB->canUseBundlerUnbundler())
2272 ++ValidBuildersSupportingBundling;
2276 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
2279 ~OffloadingActionBuilder() {
2280 for (auto *SB : SpecializedBuilders)
2284 /// Generate an action that adds device dependences (if any) to a host action.
2285 /// If no device dependence actions exist, just return the host action \a
2286 /// HostAction. If an error is found or if no builder requires the host action
2287 /// to be generated, return nullptr.
2289 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2290 phases::ID CurPhase, phases::ID FinalPhase,
2291 DeviceActionBuilder::PhasesTy &Phases) {
2295 if (SpecializedBuilders.empty())
2298 assert(HostAction && "Invalid host action!");
2300 OffloadAction::DeviceDependences DDeps;
2301 // Check if all the programming models agree we should not emit the host
2302 // action. Also, keep track of the offloading kinds employed.
2303 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2304 unsigned InactiveBuilders = 0u;
2305 unsigned IgnoringBuilders = 0u;
2306 for (auto *SB : SpecializedBuilders) {
2307 if (!SB->isValid()) {
2313 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
2315 // If the builder explicitly says the host action should be ignored,
2316 // we need to increment the variable that tracks the builders that request
2317 // the host object to be ignored.
2318 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2321 // Unless the builder was inactive for this action, we have to record the
2322 // offload kind because the host will have to use it.
2323 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2324 OffloadKind |= SB->getAssociatedOffloadKind();
2327 // If all builders agree that the host object should be ignored, just return
2329 if (IgnoringBuilders &&
2330 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2333 if (DDeps.getActions().empty())
2336 // We have dependences we need to bundle together. We use an offload action
2338 OffloadAction::HostDependence HDep(
2339 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2340 /*BoundArch=*/nullptr, DDeps);
2341 return C.MakeAction<OffloadAction>(HDep, DDeps);
2344 /// Generate an action that adds a host dependence to a device action. The
2345 /// results will be kept in this action builder. Return true if an error was
2347 bool addHostDependenceToDeviceActions(Action *&HostAction,
2348 const Arg *InputArg) {
2352 // If we are supporting bundling/unbundling and the current action is an
2353 // input action of non-source file, we replace the host action by the
2354 // unbundling action. The bundler tool has the logic to detect if an input
2355 // is a bundle or not and if the input is not a bundle it assumes it is a
2356 // host file. Therefore it is safe to create an unbundling action even if
2357 // the input is not a bundle.
2358 if (CanUseBundler && isa<InputAction>(HostAction) &&
2359 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2360 !types::isSrcFile(HostAction->getType())) {
2361 auto UnbundlingHostAction =
2362 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2363 UnbundlingHostAction->registerDependentActionInfo(
2364 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2365 /*BoundArch=*/StringRef(), Action::OFK_Host);
2366 HostAction = UnbundlingHostAction;
2369 assert(HostAction && "Invalid host action!");
2371 // Register the offload kinds that are used.
2372 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2373 for (auto *SB : SpecializedBuilders) {
2377 auto RetCode = SB->addDeviceDepences(HostAction);
2379 // Host dependences for device actions are not compatible with that same
2380 // action being ignored.
2381 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2382 "Host dependence not expected to be ignored.!");
2384 // Unless the builder was inactive for this action, we have to record the
2385 // offload kind because the host will have to use it.
2386 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2387 OffloadKind |= SB->getAssociatedOffloadKind();
2393 /// Add the offloading top level actions to the provided action list. This
2394 /// function can replace the host action by a bundling action if the
2395 /// programming models allow it.
2396 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2397 const Arg *InputArg) {
2398 // Get the device actions to be appended.
2399 ActionList OffloadAL;
2400 for (auto *SB : SpecializedBuilders) {
2403 SB->appendTopLevelActions(OffloadAL);
2406 // If we can use the bundler, replace the host action by the bundling one in
2407 // the resulting list. Otherwise, just append the device actions.
2408 if (CanUseBundler && !OffloadAL.empty()) {
2409 // Add the host action to the list in order to create the bundling action.
2410 OffloadAL.push_back(HostAction);
2412 // We expect that the host action was just appended to the action list
2413 // before this method was called.
2414 assert(HostAction == AL.back() && "Host action not in the list??");
2415 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2416 AL.back() = HostAction;
2418 AL.append(OffloadAL.begin(), OffloadAL.end());
2420 // Propagate to the current host action (if any) the offload information
2421 // associated with the current input.
2423 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2424 /*BoundArch=*/nullptr);
2428 /// Processes the host linker action. This currently consists of replacing it
2429 /// with an offload action if there are device link objects and propagate to
2430 /// the host action all the offload kinds used in the current compilation. The
2431 /// resulting action is returned.
2432 Action *processHostLinkAction(Action *HostAction) {
2433 // Add all the dependences from the device linking actions.
2434 OffloadAction::DeviceDependences DDeps;
2435 for (auto *SB : SpecializedBuilders) {
2439 SB->appendLinkDependences(DDeps);
2442 // Calculate all the offload kinds used in the current compilation.
2443 unsigned ActiveOffloadKinds = 0u;
2444 for (auto &I : InputArgToOffloadKindMap)
2445 ActiveOffloadKinds |= I.second;
2447 // If we don't have device dependencies, we don't have to create an offload
2449 if (DDeps.getActions().empty()) {
2450 // Propagate all the active kinds to host action. Given that it is a link
2451 // action it is assumed to depend on all actions generated so far.
2452 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2453 /*BoundArch=*/nullptr);
2457 // Create the offload action with all dependences. When an offload action
2458 // is created the kinds are propagated to the host action, so we don't have
2459 // to do that explicitly here.
2460 OffloadAction::HostDependence HDep(
2461 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2462 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2463 return C.MakeAction<OffloadAction>(HDep, DDeps);
2466 } // anonymous namespace.
2468 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2469 const InputList &Inputs, ActionList &Actions) const {
2470 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
2472 if (!SuppressMissingInputWarning && Inputs.empty()) {
2473 Diag(clang::diag::err_drv_no_input_files);
2478 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
2480 if (FinalPhase == phases::Link) {
2481 if (Args.hasArg(options::OPT_emit_llvm))
2482 Diag(clang::diag::err_drv_emit_llvm_link);
2483 if (IsCLMode() && LTOMode != LTOK_None &&
2484 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2485 Diag(clang::diag::err_drv_lto_without_lld);
2488 // Reject -Z* at the top level, these options should never have been exposed
2490 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
2491 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
2493 // Diagnose misuse of /Fo.
2494 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
2495 StringRef V = A->getValue();
2496 if (Inputs.size() > 1 && !V.empty() &&
2497 !llvm::sys::path::is_separator(V.back())) {
2498 // Check whether /Fo tries to name an output file for multiple inputs.
2499 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2500 << A->getSpelling() << V;
2501 Args.eraseArg(options::OPT__SLASH_Fo);
2505 // Diagnose misuse of /Fa.
2506 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2507 StringRef V = A->getValue();
2508 if (Inputs.size() > 1 && !V.empty() &&
2509 !llvm::sys::path::is_separator(V.back())) {
2510 // Check whether /Fa tries to name an asm file for multiple inputs.
2511 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2512 << A->getSpelling() << V;
2513 Args.eraseArg(options::OPT__SLASH_Fa);
2517 // Diagnose misuse of /o.
2518 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2519 if (A->getValue()[0] == '\0') {
2520 // It has to have a value.
2521 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2522 Args.eraseArg(options::OPT__SLASH_o);
2526 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2527 // * no filename after it
2528 // * both /Yc and /Yu passed but with different filenames
2529 // * corresponding file not also passed as /FI
2530 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2531 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2532 if (YcArg && YcArg->getValue()[0] == '\0') {
2533 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2534 Args.eraseArg(options::OPT__SLASH_Yc);
2537 if (YuArg && YuArg->getValue()[0] == '\0') {
2538 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2539 Args.eraseArg(options::OPT__SLASH_Yu);
2542 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2543 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2544 Args.eraseArg(options::OPT__SLASH_Yc);
2545 Args.eraseArg(options::OPT__SLASH_Yu);
2546 YcArg = YuArg = nullptr;
2548 if (YcArg || YuArg) {
2549 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2550 bool FoundMatchingInclude = false;
2551 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2552 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2553 if (Inc->getValue() == Val)
2554 FoundMatchingInclude = true;
2556 if (!FoundMatchingInclude) {
2557 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2558 << (YcArg ? YcArg : YuArg)->getSpelling();
2559 Args.eraseArg(options::OPT__SLASH_Yc);
2560 Args.eraseArg(options::OPT__SLASH_Yu);
2561 YcArg = YuArg = nullptr;
2564 if (YcArg && Inputs.size() > 1) {
2565 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2566 Args.eraseArg(options::OPT__SLASH_Yc);
2569 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2570 // /Y- disables all pch handling. Rather than check for it everywhere,
2571 // just remove clang-cl pch-related flags here.
2572 Args.eraseArg(options::OPT__SLASH_Fp);
2573 Args.eraseArg(options::OPT__SLASH_Yc);
2574 Args.eraseArg(options::OPT__SLASH_Yu);
2575 YcArg = YuArg = nullptr;
2578 // Builder to be used to build offloading actions.
2579 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
2581 // Construct the actions to perform.
2582 ActionList LinkerInputs;
2584 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
2585 for (auto &I : Inputs) {
2586 types::ID InputType = I.first;
2587 const Arg *InputArg = I.second;
2590 types::getCompilationPhases(InputType, PL);
2592 // If the first step comes after the final phase we are doing as part of
2593 // this compilation, warn the user about it.
2594 phases::ID InitialPhase = PL[0];
2595 if (InitialPhase > FinalPhase) {
2596 // Claim here to avoid the more general unused warning.
2599 // Suppress all unused style warnings with -Qunused-arguments
2600 if (Args.hasArg(options::OPT_Qunused_arguments))
2603 // Special case when final phase determined by binary name, rather than
2604 // by a command-line argument with a corresponding Arg.
2606 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
2607 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
2608 // Special case '-E' warning on a previously preprocessed file to make
2610 else if (InitialPhase == phases::Compile &&
2611 FinalPhase == phases::Preprocess &&
2612 getPreprocessedType(InputType) == types::TY_INVALID)
2613 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
2614 << InputArg->getAsString(Args) << !!FinalPhaseArg
2615 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2617 Diag(clang::diag::warn_drv_input_file_unused)
2618 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2620 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2625 // Add a separate precompile phase for the compile phase.
2626 if (FinalPhase >= phases::Compile) {
2627 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
2628 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
2629 types::getCompilationPhases(HeaderType, PCHPL);
2630 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
2632 // Build the pipeline for the pch file.
2633 Action *ClangClPch =
2634 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
2635 for (phases::ID Phase : PCHPL)
2636 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2638 Actions.push_back(ClangClPch);
2639 // The driver currently exits after the first failed command. This
2640 // relies on that behavior, to make sure if the pch generation fails,
2641 // the main compilation won't run.
2645 // Build the pipeline for this file.
2646 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
2648 // Use the current host action in any of the offloading actions, if
2650 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2653 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2655 phases::ID Phase = *i;
2657 // We are done if this step is past what the user requested.
2658 if (Phase > FinalPhase)
2661 // Add any offload action the host action depends on.
2662 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2663 Current, InputArg, Phase, FinalPhase, PL);
2667 // Queue linker inputs.
2668 if (Phase == phases::Link) {
2669 assert((i + 1) == e && "linking must be final compilation step.");
2670 LinkerInputs.push_back(Current);
2675 // Otherwise construct the appropriate action.
2676 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2678 // We didn't create a new action, so we will just move to the next phase.
2679 if (NewCurrent == Current)
2682 Current = NewCurrent;
2684 // Use the current host action in any of the offloading actions, if
2686 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2689 if (Current->getType() == types::TY_Nothing)
2693 // If we ended with something, add to the output list.
2695 Actions.push_back(Current);
2697 // Add any top level actions generated for offloading.
2698 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
2701 // Add a link action if necessary.
2702 if (!LinkerInputs.empty()) {
2703 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2704 LA = OffloadBuilder.processHostLinkAction(LA);
2705 Actions.push_back(LA);
2708 // If we are linking, claim any options which are obviously only used for
2710 if (FinalPhase == phases::Link && PL.size() == 1) {
2711 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
2712 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2715 // Claim ignored clang-cl options.
2716 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
2718 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2719 // to non-CUDA compilations and should not trigger warnings there.
2720 Args.ClaimAllArgs(options::OPT_cuda_host_only);
2721 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
2724 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2725 phases::ID Phase, Action *Input) const {
2726 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
2728 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2729 // encode this in the steps because the intermediate type depends on
2730 // arguments. Just special case here.
2731 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2734 // Build the appropriate action.
2737 llvm_unreachable("link action invalid here.");
2738 case phases::Preprocess: {
2740 // -{M, MM} alter the output type.
2741 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
2742 OutputTy = types::TY_Dependencies;
2744 OutputTy = Input->getType();
2745 if (!Args.hasFlag(options::OPT_frewrite_includes,
2746 options::OPT_fno_rewrite_includes, false) &&
2747 !Args.hasFlag(options::OPT_frewrite_imports,
2748 options::OPT_fno_rewrite_imports, false) &&
2750 OutputTy = types::getPreprocessedType(OutputTy);
2751 assert(OutputTy != types::TY_INVALID &&
2752 "Cannot preprocess this input type!");
2754 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
2756 case phases::Precompile: {
2757 types::ID OutputTy = getPrecompiledType(Input->getType());
2758 assert(OutputTy != types::TY_INVALID &&
2759 "Cannot precompile this input type!");
2760 if (Args.hasArg(options::OPT_fsyntax_only)) {
2761 // Syntax checks should not emit a PCH file
2762 OutputTy = types::TY_Nothing;
2764 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
2766 case phases::Compile: {
2767 if (Args.hasArg(options::OPT_fsyntax_only))
2768 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
2769 if (Args.hasArg(options::OPT_rewrite_objc))
2770 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
2771 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
2772 return C.MakeAction<CompileJobAction>(Input,
2773 types::TY_RewrittenLegacyObjC);
2774 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
2775 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
2776 if (Args.hasArg(options::OPT__migrate))
2777 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
2778 if (Args.hasArg(options::OPT_emit_ast))
2779 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
2780 if (Args.hasArg(options::OPT_module_file_info))
2781 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
2782 if (Args.hasArg(options::OPT_verify_pch))
2783 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2784 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
2786 case phases::Backend: {
2789 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
2790 return C.MakeAction<BackendJobAction>(Input, Output);
2792 if (Args.hasArg(options::OPT_emit_llvm)) {
2794 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
2795 return C.MakeAction<BackendJobAction>(Input, Output);
2797 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
2799 case phases::Assemble:
2800 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
2803 llvm_unreachable("invalid phase in ConstructPhaseAction");
2806 void Driver::BuildJobs(Compilation &C) const {
2807 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2809 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2811 // It is an error to provide a -o option if we are making multiple output
2814 unsigned NumOutputs = 0;
2815 for (const Action *A : C.getActions())
2816 if (A->getType() != types::TY_Nothing)
2819 if (NumOutputs > 1) {
2820 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
2821 FinalOutput = nullptr;
2825 // Collect the list of architectures.
2826 llvm::StringSet<> ArchNames;
2827 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2828 for (const Arg *A : C.getArgs())
2829 if (A->getOption().matches(options::OPT_arch))
2830 ArchNames.insert(A->getValue());
2832 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2833 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
2834 for (Action *A : C.getActions()) {
2835 // If we are linking an image for multiple archs then the linker wants
2836 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2837 // doesn't fit in cleanly because we have to pass this information down.
2839 // FIXME: This is a hack; find a cleaner way to integrate this into the
2841 const char *LinkingOutput = nullptr;
2842 if (isa<LipoJobAction>(A)) {
2844 LinkingOutput = FinalOutput->getValue();
2846 LinkingOutput = getDefaultImageName();
2849 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
2850 /*BoundArch*/ StringRef(),
2851 /*AtTopLevel*/ true,
2852 /*MultipleArchs*/ ArchNames.size() > 1,
2853 /*LinkingOutput*/ LinkingOutput, CachedResults,
2854 /*TargetDeviceOffloadKind*/ Action::OFK_None);
2857 // If the user passed -Qunused-arguments or there were errors, don't warn
2858 // about any unused arguments.
2859 if (Diags.hasErrorOccurred() ||
2860 C.getArgs().hasArg(options::OPT_Qunused_arguments))
2864 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
2866 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
2867 (void)C.getArgs().hasArg(options::OPT_driver_mode);
2868 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
2870 for (Arg *A : C.getArgs()) {
2871 // FIXME: It would be nice to be able to send the argument to the
2872 // DiagnosticsEngine, so that extra values, position, and so on could be
2874 if (!A->isClaimed()) {
2875 if (A->getOption().hasFlag(options::NoArgumentUnused))
2878 // Suppress the warning automatically if this is just a flag, and it is an
2879 // instance of an argument we already claimed.
2880 const Option &Opt = A->getOption();
2881 if (Opt.getKind() == Option::FlagClass) {
2882 bool DuplicateClaimed = false;
2884 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2885 if (AA->isClaimed()) {
2886 DuplicateClaimed = true;
2891 if (DuplicateClaimed)
2895 // In clang-cl, don't mention unknown arguments here since they have
2896 // already been warned about.
2897 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2898 Diag(clang::diag::warn_drv_unused_argument)
2899 << A->getAsString(C.getArgs());
2905 /// Utility class to control the collapse of dependent actions and select the
2906 /// tools accordingly.
2907 class ToolSelector final {
2908 /// The tool chain this selector refers to.
2909 const ToolChain &TC;
2911 /// The compilation this selector refers to.
2912 const Compilation &C;
2914 /// The base action this selector refers to.
2915 const JobAction *BaseAction;
2917 /// Set to true if the current toolchain refers to host actions.
2918 bool IsHostSelector;
2920 /// Set to true if save-temps and embed-bitcode functionalities are active.
2924 /// Get previous dependent action or null if that does not exist. If
2925 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2926 /// null will be returned.
2927 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2928 ActionList &SavedOffloadAction,
2929 bool CanBeCollapsed = true) {
2930 // An option can be collapsed only if it has a single input.
2931 if (Inputs.size() != 1)
2934 Action *CurAction = *Inputs.begin();
2935 if (CanBeCollapsed &&
2936 !CurAction->isCollapsingWithNextDependentActionLegal())
2939 // If the input action is an offload action. Look through it and save any
2940 // offload action that can be dropped in the event of a collapse.
2941 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2942 // If the dependent action is a device action, we will attempt to collapse
2943 // only with other device actions. Otherwise, we would do the same but
2944 // with host actions only.
2945 if (!IsHostSelector) {
2946 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2948 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2949 if (CanBeCollapsed &&
2950 !CurAction->isCollapsingWithNextDependentActionLegal())
2952 SavedOffloadAction.push_back(OA);
2953 return dyn_cast<JobAction>(CurAction);
2955 } else if (OA->hasHostDependence()) {
2956 CurAction = OA->getHostDependence();
2957 if (CanBeCollapsed &&
2958 !CurAction->isCollapsingWithNextDependentActionLegal())
2960 SavedOffloadAction.push_back(OA);
2961 return dyn_cast<JobAction>(CurAction);
2966 return dyn_cast<JobAction>(CurAction);
2969 /// Return true if an assemble action can be collapsed.
2970 bool canCollapseAssembleAction() const {
2971 return TC.useIntegratedAs() && !SaveTemps &&
2972 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2973 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2974 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2977 /// Return true if a preprocessor action can be collapsed.
2978 bool canCollapsePreprocessorAction() const {
2979 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2980 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2981 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2984 /// Struct that relates an action with the offload actions that would be
2985 /// collapsed with it.
2986 struct JobActionInfo final {
2987 /// The action this info refers to.
2988 const JobAction *JA = nullptr;
2989 /// The offload actions we need to take care off if this action is
2991 ActionList SavedOffloadAction;
2994 /// Append collapsed offload actions from the give nnumber of elements in the
2995 /// action info array.
2996 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2997 ArrayRef<JobActionInfo> &ActionInfo,
2998 unsigned ElementNum) {
2999 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3000 for (unsigned I = 0; I < ElementNum; ++I)
3001 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3002 ActionInfo[I].SavedOffloadAction.end());
3005 /// Functions that attempt to perform the combining. They detect if that is
3006 /// legal, and if so they update the inputs \a Inputs and the offload action
3007 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3008 /// the combined action is returned. If the combining is not legal or if the
3009 /// tool does not exist, null is returned.
3010 /// Currently three kinds of collapsing are supported:
3011 /// - Assemble + Backend + Compile;
3012 /// - Assemble + Backend ;
3013 /// - Backend + Compile.
3015 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3016 const ActionList *&Inputs,
3017 ActionList &CollapsedOffloadAction) {
3018 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3020 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3021 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3022 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3023 if (!AJ || !BJ || !CJ)
3026 // Get compiler tool.
3027 const Tool *T = TC.SelectTool(*CJ);
3031 // When using -fembed-bitcode, it is required to have the same tool (clang)
3032 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3034 const Tool *BT = TC.SelectTool(*BJ);
3039 if (!T->hasIntegratedAssembler())
3042 Inputs = &CJ->getInputs();
3043 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3047 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3048 const ActionList *&Inputs,
3049 ActionList &CollapsedOffloadAction) {
3050 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3052 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3053 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3057 // Retrieve the compile job, backend action must always be preceded by one.
3058 ActionList CompileJobOffloadActions;
3059 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3060 /*CanBeCollapsed=*/false);
3061 if (!AJ || !BJ || !CJ)
3064 assert(isa<CompileJobAction>(CJ) &&
3065 "Expecting compile job preceding backend job.");
3067 // Get compiler tool.
3068 const Tool *T = TC.SelectTool(*CJ);
3072 if (!T->hasIntegratedAssembler())
3075 Inputs = &BJ->getInputs();
3076 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3080 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3081 const ActionList *&Inputs,
3082 ActionList &CollapsedOffloadAction) {
3083 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3085 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3086 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3090 // Get compiler tool.
3091 const Tool *T = TC.SelectTool(*CJ);
3095 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3098 Inputs = &CJ->getInputs();
3099 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3104 /// Updates the inputs if the obtained tool supports combining with
3105 /// preprocessor action, and the current input is indeed a preprocessor
3106 /// action. If combining results in the collapse of offloading actions, those
3107 /// are appended to \a CollapsedOffloadAction.
3108 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3109 ActionList &CollapsedOffloadAction) {
3110 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3113 // Attempt to get a preprocessor action dependence.
3114 ActionList PreprocessJobOffloadActions;
3115 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3116 if (!PJ || !isa<PreprocessJobAction>(PJ))
3119 // This is legal to combine. Append any offload action we found and set the
3120 // current inputs to preprocessor inputs.
3121 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3122 PreprocessJobOffloadActions.end());
3123 Inputs = &PJ->getInputs();
3127 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3128 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3129 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3130 EmbedBitcode(EmbedBitcode) {
3131 assert(BaseAction && "Invalid base action.");
3132 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3135 /// Check if a chain of actions can be combined and return the tool that can
3136 /// handle the combination of actions. The pointer to the current inputs \a
3137 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3138 /// connected to collapsed actions are updated accordingly. The latter enables
3139 /// the caller of the selector to process them afterwards instead of just
3140 /// dropping them. If no suitable tool is found, null will be returned.
3141 const Tool *getTool(const ActionList *&Inputs,
3142 ActionList &CollapsedOffloadAction) {
3144 // Get the largest chain of actions that we could combine.
3147 SmallVector<JobActionInfo, 5> ActionChain(1);
3148 ActionChain.back().JA = BaseAction;
3149 while (ActionChain.back().JA) {
3150 const Action *CurAction = ActionChain.back().JA;
3152 // Grow the chain by one element.
3153 ActionChain.resize(ActionChain.size() + 1);
3154 JobActionInfo &AI = ActionChain.back();
3156 // Attempt to fill it with the
3158 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
3161 // Pop the last action info as it could not be filled.
3162 ActionChain.pop_back();
3165 // Attempt to combine actions. If all combining attempts failed, just return
3166 // the tool of the provided action. At the end we attempt to combine the
3167 // action with any preprocessor action it may depend on.
3170 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3171 CollapsedOffloadAction);
3173 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3175 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3177 Inputs = &BaseAction->getInputs();
3178 T = TC.SelectTool(*BaseAction);
3181 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3187 /// Return a string that uniquely identifies the result of a job. The bound arch
3188 /// is not necessarily represented in the toolchain's triple -- for example,
3189 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
3190 /// Also, we need to add the offloading device kind, as the same tool chain can
3191 /// be used for host and device for some programming models, e.g. OpenMP.
3192 static std::string GetTriplePlusArchString(const ToolChain *TC,
3193 StringRef BoundArch,
3194 Action::OffloadKind OffloadKind) {
3195 std::string TriplePlusArch = TC->getTriple().normalize();
3196 if (!BoundArch.empty()) {
3197 TriplePlusArch += "-";
3198 TriplePlusArch += BoundArch;
3200 TriplePlusArch += "-";
3201 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3202 return TriplePlusArch;
3205 InputInfo Driver::BuildJobsForAction(
3206 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3207 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3208 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3209 Action::OffloadKind TargetDeviceOffloadKind) const {
3210 std::pair<const Action *, std::string> ActionTC = {
3211 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3212 auto CachedResult = CachedResults.find(ActionTC);
3213 if (CachedResult != CachedResults.end()) {
3214 return CachedResult->second;
3216 InputInfo Result = BuildJobsForActionNoCache(
3217 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
3218 CachedResults, TargetDeviceOffloadKind);
3219 CachedResults[ActionTC] = Result;
3223 InputInfo Driver::BuildJobsForActionNoCache(
3224 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3225 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3226 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3227 Action::OffloadKind TargetDeviceOffloadKind) const {
3228 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3230 InputInfoList OffloadDependencesInputInfo;
3231 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
3232 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3233 // The offload action is expected to be used in four different situations.
3235 // a) Set a toolchain/architecture/kind for a host action:
3236 // Host Action 1 -> OffloadAction -> Host Action 2
3238 // b) Set a toolchain/architecture/kind for a device action;
3239 // Device Action 1 -> OffloadAction -> Device Action 2
3241 // c) Specify a device dependence to a host action;
3242 // Device Action 1 _
3244 // Host Action 1 ---> OffloadAction -> Host Action 2
3246 // d) Specify a host dependence to a device action.
3249 // Device Action 1 ---> OffloadAction -> Device Action 2
3251 // For a) and b), we just return the job generated for the dependence. For
3252 // c) and d) we override the current action with the host/device dependence
3253 // if the current toolchain is host/device and set the offload dependences
3254 // info with the jobs obtained from the device/host dependence(s).
3256 // If there is a single device option, just generate the job for it.
3257 if (OA->hasSingleDeviceDependence()) {
3259 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3260 const char *DepBoundArch) {
3262 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3263 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
3264 CachedResults, DepA->getOffloadingDeviceKind());
3269 // If 'Action 2' is host, we generate jobs for the device dependences and
3270 // override the current action with the host dependence. Otherwise, we
3271 // generate the host dependences and override the action with the device
3272 // dependence. The dependences can't therefore be a top-level action.
3273 OA->doOnEachDependence(
3274 /*IsHostDependence=*/BuildingForOffloadDevice,
3275 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3276 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3277 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3278 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
3279 DepA->getOffloadingDeviceKind()));
3282 A = BuildingForOffloadDevice
3283 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3284 : OA->getHostDependence();
3287 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
3288 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3289 // just using Args was better?
3290 const Arg &Input = IA->getInputArg();
3292 if (Input.getOption().matches(options::OPT_INPUT)) {
3293 const char *Name = Input.getValue();
3294 return InputInfo(A, Name, /* BaseInput = */ Name);
3296 return InputInfo(A, &Input, /* BaseInput = */ "");
3299 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
3300 const ToolChain *TC;
3301 StringRef ArchName = BAA->getArchName();
3303 if (!ArchName.empty())
3304 TC = &getToolChain(C.getArgs(),
3305 computeTargetTriple(*this, DefaultTargetTriple,
3306 C.getArgs(), ArchName));
3308 TC = &C.getDefaultToolChain();
3310 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
3311 MultipleArchs, LinkingOutput, CachedResults,
3312 TargetDeviceOffloadKind);
3316 const ActionList *Inputs = &A->getInputs();
3318 const JobAction *JA = cast<JobAction>(A);
3319 ActionList CollapsedOffloadActions;
3321 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3322 embedBitcodeInObject() && !isUsingLTO());
3323 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3328 // If we've collapsed action list that contained OffloadAction we
3329 // need to build jobs for host/device-side inputs it may have held.
3330 for (const auto *OA : CollapsedOffloadActions)
3331 cast<OffloadAction>(OA)->doOnEachDependence(
3332 /*IsHostDependence=*/BuildingForOffloadDevice,
3333 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3334 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3335 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
3336 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
3337 DepA->getOffloadingDeviceKind()));
3340 // Only use pipes when there is exactly one input.
3341 InputInfoList InputInfos;
3342 for (const Action *Input : *Inputs) {
3343 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3344 // shouldn't get temporary output names.
3345 // FIXME: Clean this up.
3346 bool SubJobAtTopLevel =
3347 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
3348 InputInfos.push_back(BuildJobsForAction(
3349 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
3350 CachedResults, A->getOffloadingDeviceKind()));
3353 // Always use the first input as the base input.
3354 const char *BaseInput = InputInfos[0].getBaseInput();
3356 // ... except dsymutil actions, which use their actual input as the base
3358 if (JA->getType() == types::TY_dSYM)
3359 BaseInput = InputInfos[0].getFilename();
3361 // Append outputs of offload device jobs to the input list
3362 if (!OffloadDependencesInputInfo.empty())
3363 InputInfos.append(OffloadDependencesInputInfo.begin(),
3364 OffloadDependencesInputInfo.end());
3366 // Set the effective triple of the toolchain for the duration of this job.
3367 llvm::Triple EffectiveTriple;
3368 const ToolChain &ToolTC = T->getToolChain();
3369 const ArgList &Args =
3370 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
3371 if (InputInfos.size() != 1) {
3372 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3374 // Pass along the input type if it can be unambiguously determined.
3375 EffectiveTriple = llvm::Triple(
3376 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3378 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3380 // Determine the place to write output to, if any.
3382 InputInfoList UnbundlingResults;
3383 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3384 // If we have an unbundling job, we need to create results for all the
3385 // outputs. We also update the results cache so that other actions using
3386 // this unbundling action can get the right results.
3387 for (auto &UI : UA->getDependentActionsInfo()) {
3388 assert(UI.DependentOffloadKind != Action::OFK_None &&
3389 "Unbundling with no offloading??");
3391 // Unbundling actions are never at the top level. When we generate the
3392 // offloading prefix, we also do that for the host file because the
3393 // unbundling action does not change the type of the output which can
3394 // cause a overwrite.
3395 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3396 UI.DependentOffloadKind,
3397 UI.DependentToolChain->getTriple().normalize(),
3398 /*CreatePrefixForHost=*/true);
3399 auto CurI = InputInfo(
3400 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3401 /*AtTopLevel=*/false, MultipleArchs,
3404 // Save the unbundling result.
3405 UnbundlingResults.push_back(CurI);
3407 // Get the unique string identifier for this dependence and cache the
3409 CachedResults[{A, GetTriplePlusArchString(
3410 UI.DependentToolChain, UI.DependentBoundArch,
3411 UI.DependentOffloadKind)}] = CurI;
3414 // Now that we have all the results generated, select the one that should be
3415 // returned for the current depending action.
3416 std::pair<const Action *, std::string> ActionTC = {
3417 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3418 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3419 "Result does not exist??");
3420 Result = CachedResults[ActionTC];
3421 } else if (JA->getType() == types::TY_Nothing)
3422 Result = InputInfo(A, BaseInput);
3424 // We only have to generate a prefix for the host if this is not a top-level
3426 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3427 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3428 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3430 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
3431 AtTopLevel, MultipleArchs,
3436 if (CCCPrintBindings && !CCGenDiagnostics) {
3437 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3438 << " - \"" << T->getName() << "\", inputs: [";
3439 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3440 llvm::errs() << InputInfos[i].getAsString();
3442 llvm::errs() << ", ";
3444 if (UnbundlingResults.empty())
3445 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3447 llvm::errs() << "], outputs: [";
3448 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3449 llvm::errs() << UnbundlingResults[i].getAsString();
3451 llvm::errs() << ", ";
3453 llvm::errs() << "] \n";
3456 if (UnbundlingResults.empty())
3458 C, *JA, Result, InputInfos,
3459 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3462 T->ConstructJobMultipleOutputs(
3463 C, *JA, UnbundlingResults, InputInfos,
3464 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3470 const char *Driver::getDefaultImageName() const {
3471 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3472 return Target.isOSWindows() ? "a.exe" : "a.out";
3475 /// \brief Create output filename based on ArgValue, which could either be a
3476 /// full filename, filename without extension, or a directory. If ArgValue
3477 /// does not provide a filename, then use BaseName, and use the extension
3478 /// suitable for FileType.
3479 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
3481 types::ID FileType) {
3482 SmallString<128> Filename = ArgValue;
3484 if (ArgValue.empty()) {
3485 // If the argument is empty, output to BaseName in the current dir.
3486 Filename = BaseName;
3487 } else if (llvm::sys::path::is_separator(Filename.back())) {
3488 // If the argument is a directory, output to BaseName in that dir.
3489 llvm::sys::path::append(Filename, BaseName);
3492 if (!llvm::sys::path::has_extension(ArgValue)) {
3493 // If the argument didn't provide an extension, then set it.
3494 const char *Extension = types::getTypeTempSuffix(FileType, true);
3496 if (FileType == types::TY_Image &&
3497 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3498 // The output file is a dll.
3502 llvm::sys::path::replace_extension(Filename, Extension);
3505 return Args.MakeArgString(Filename.c_str());
3508 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
3509 const char *BaseInput,
3510 StringRef BoundArch, bool AtTopLevel,
3512 StringRef OffloadingPrefix) const {
3513 llvm::PrettyStackTraceString CrashInfo("Computing output path");
3514 // Output to a user requested destination?
3515 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
3516 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
3517 return C.addResultFile(FinalOutput->getValue(), &JA);
3520 // For /P, preprocess to file named after BaseInput.
3521 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3522 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3523 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3525 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
3526 NameArg = A->getValue();
3527 return C.addResultFile(
3528 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3532 // Default to writing to stdout?
3533 if (AtTopLevel && !CCGenDiagnostics &&
3534 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
3537 // Is this the assembly listing for /FA?
3538 if (JA.getType() == types::TY_PP_Asm &&
3539 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3540 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3541 // Use /Fa and the input filename to determine the asm file name.
3542 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3543 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
3544 return C.addResultFile(
3545 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3549 // Output to a temporary file?
3550 if ((!AtTopLevel && !isSaveTempsEnabled() &&
3551 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
3553 StringRef Name = llvm::sys::path::filename(BaseInput);
3554 std::pair<StringRef, StringRef> Split = Name.split('.');
3555 std::string TmpName = GetTemporaryPath(
3556 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3557 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3560 SmallString<128> BasePath(BaseInput);
3563 // Dsymutil actions should use the full path.
3564 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
3565 BaseName = BasePath;
3567 BaseName = llvm::sys::path::filename(BasePath);
3569 // Determine what the derived output name should be.
3570 const char *NamedOutput;
3572 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
3573 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3574 // The /Fo or /o flag decides the object filename.
3577 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3580 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
3581 } else if (JA.getType() == types::TY_Image &&
3582 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3583 options::OPT__SLASH_o)) {
3584 // The /Fe or /o flag names the linked file.
3587 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3590 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
3591 } else if (JA.getType() == types::TY_Image) {
3593 // clang-cl uses BaseName for the executable name.
3595 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
3597 SmallString<128> Output(getDefaultImageName());
3598 Output += OffloadingPrefix;
3599 if (MultipleArchs && !BoundArch.empty()) {
3601 Output.append(BoundArch);
3603 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
3605 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
3606 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
3608 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
3609 assert(Suffix && "All types used for output should have a suffix.");
3611 std::string::size_type End = std::string::npos;
3612 if (!types::appendSuffixForType(JA.getType()))
3613 End = BaseName.rfind('.');
3614 SmallString<128> Suffixed(BaseName.substr(0, End));
3615 Suffixed += OffloadingPrefix;
3616 if (MultipleArchs && !BoundArch.empty()) {
3618 Suffixed.append(BoundArch);
3620 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3621 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3622 // optimized bitcode output.
3623 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3624 JA.getType() == types::TY_LLVM_BC)
3628 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3631 // Prepend object file path if -save-temps=obj
3632 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3633 JA.getType() != types::TY_PCH) {
3634 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3635 SmallString<128> TempPath(FinalOutput->getValue());
3636 llvm::sys::path::remove_filename(TempPath);
3637 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3638 llvm::sys::path::append(TempPath, OutputFileName);
3639 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3642 // If we're saving temps and the temp file conflicts with the input file,
3643 // then avoid overwriting input file.
3644 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
3645 bool SameFile = false;
3646 SmallString<256> Result;
3647 llvm::sys::fs::current_path(Result);
3648 llvm::sys::path::append(Result, BaseName);
3649 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3650 // Must share the same path to conflict.
3652 StringRef Name = llvm::sys::path::filename(BaseInput);
3653 std::pair<StringRef, StringRef> Split = Name.split('.');
3654 std::string TmpName = GetTemporaryPath(
3655 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3656 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3660 // As an annoying special case, PCH generation doesn't strip the pathname.
3661 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
3662 llvm::sys::path::remove_filename(BasePath);
3663 if (BasePath.empty())
3664 BasePath = NamedOutput;
3666 llvm::sys::path::append(BasePath, NamedOutput);
3667 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
3669 return C.addResultFile(NamedOutput, &JA);
3673 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
3674 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3675 // attempting to use this prefix when looking for file paths.
3676 for (const std::string &Dir : PrefixDirs) {
3679 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3680 llvm::sys::path::append(P, Name);
3681 if (llvm::sys::fs::exists(Twine(P)))
3685 SmallString<128> P(ResourceDir);
3686 llvm::sys::path::append(P, Name);
3687 if (llvm::sys::fs::exists(Twine(P)))
3690 for (const std::string &Dir : TC.getFilePaths()) {
3693 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3694 llvm::sys::path::append(P, Name);
3695 if (llvm::sys::fs::exists(Twine(P)))
3702 void Driver::generatePrefixedToolNames(
3703 StringRef Tool, const ToolChain &TC,
3704 SmallVectorImpl<std::string> &Names) const {
3705 // FIXME: Needs a better variable than DefaultTargetTriple
3706 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
3707 Names.emplace_back(Tool);
3709 // Allow the discovery of tools prefixed with LLVM's default target triple.
3710 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3711 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
3712 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
3715 static bool ScanDirForExecutable(SmallString<128> &Dir,
3716 ArrayRef<std::string> Names) {
3717 for (const auto &Name : Names) {
3718 llvm::sys::path::append(Dir, Name);
3719 if (llvm::sys::fs::can_execute(Twine(Dir)))
3721 llvm::sys::path::remove_filename(Dir);
3726 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
3727 SmallVector<std::string, 2> TargetSpecificExecutables;
3728 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3730 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3731 // attempting to use this prefix when looking for program paths.
3732 for (const auto &PrefixDir : PrefixDirs) {
3733 if (llvm::sys::fs::is_directory(PrefixDir)) {
3734 SmallString<128> P(PrefixDir);
3735 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3738 SmallString<128> P((PrefixDir + Name).str());
3739 if (llvm::sys::fs::can_execute(Twine(P)))
3744 const ToolChain::path_list &List = TC.getProgramPaths();
3745 for (const auto &Path : List) {
3746 SmallString<128> P(Path);
3747 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3751 // If all else failed, search the path.
3752 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3753 if (llvm::ErrorOr<std::string> P =
3754 llvm::sys::findProgramByName(TargetSpecificExecutable))
3760 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
3761 SmallString<128> Path;
3762 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
3764 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
3771 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3772 SmallString<128> Output;
3773 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3774 // FIXME: If anybody needs it, implement this obscure rule:
3775 // "If you specify a directory without a file name, the default file name
3776 // is VCx0.pch., where x is the major version of Visual C++ in use."
3777 Output = FpArg->getValue();
3779 // "If you do not specify an extension as part of the path name, an
3780 // extension of .pch is assumed. "
3781 if (!llvm::sys::path::has_extension(Output))
3785 llvm::sys::path::replace_extension(Output, ".pch");
3787 return Output.str();
3790 const ToolChain &Driver::getToolChain(const ArgList &Args,
3791 const llvm::Triple &Target) const {
3793 auto &TC = ToolChains[Target.str()];
3795 switch (Target.getOS()) {
3796 case llvm::Triple::Haiku:
3797 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
3799 case llvm::Triple::Ananas:
3800 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
3802 case llvm::Triple::CloudABI:
3803 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
3805 case llvm::Triple::Darwin:
3806 case llvm::Triple::MacOSX:
3807 case llvm::Triple::IOS:
3808 case llvm::Triple::TvOS:
3809 case llvm::Triple::WatchOS:
3810 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
3812 case llvm::Triple::DragonFly:
3813 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
3815 case llvm::Triple::OpenBSD:
3816 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
3818 case llvm::Triple::Bitrig:
3819 TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args);
3821 case llvm::Triple::NetBSD:
3822 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
3824 case llvm::Triple::FreeBSD:
3825 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
3827 case llvm::Triple::Minix:
3828 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
3830 case llvm::Triple::Linux:
3831 case llvm::Triple::ELFIAMCU:
3832 if (Target.getArch() == llvm::Triple::hexagon)
3833 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3835 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3836 !Target.hasEnvironment())
3837 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3840 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
3842 case llvm::Triple::NaCl:
3843 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
3845 case llvm::Triple::Fuchsia:
3846 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
3848 case llvm::Triple::Solaris:
3849 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
3851 case llvm::Triple::AMDHSA:
3852 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
3854 case llvm::Triple::Win32:
3855 switch (Target.getEnvironment()) {
3857 if (Target.isOSBinFormatELF())
3858 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3859 else if (Target.isOSBinFormatMachO())
3860 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3862 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3864 case llvm::Triple::GNU:
3865 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
3867 case llvm::Triple::Itanium:
3868 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3871 case llvm::Triple::MSVC:
3872 case llvm::Triple::UnknownEnvironment:
3873 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
3877 case llvm::Triple::PS4:
3878 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
3880 case llvm::Triple::Contiki:
3881 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
3884 // Of these targets, Hexagon is the only one that might have
3885 // an OS of Linux, in which case it got handled above already.
3886 switch (Target.getArch()) {
3887 case llvm::Triple::tce:
3888 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
3890 case llvm::Triple::tcele:
3891 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
3893 case llvm::Triple::hexagon:
3894 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3897 case llvm::Triple::lanai:
3898 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
3900 case llvm::Triple::xcore:
3901 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
3903 case llvm::Triple::wasm32:
3904 case llvm::Triple::wasm64:
3905 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
3907 case llvm::Triple::avr:
3908 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
3911 if (Target.getVendor() == llvm::Triple::Myriad)
3912 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3914 else if (toolchains::BareMetal::handlesTarget(Target))
3915 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
3916 else if (Target.isOSBinFormatELF())
3917 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3918 else if (Target.isOSBinFormatMachO())
3919 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3921 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3926 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3927 // compiles always need two toolchains, the CUDA toolchain and the host
3928 // toolchain. So the only valid way to create a CUDA toolchain is via
3929 // CreateOffloadingDeviceToolChains.
3934 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
3935 // Say "no" if there is not exactly one input of a type clang understands.
3936 if (JA.size() != 1 ||
3937 !types::isAcceptedByClang((*JA.input_begin())->getType()))
3940 // And say "no" if this is not a kind of action clang understands.
3941 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
3942 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
3948 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3949 /// grouped values as integers. Numbers which are not provided are set to 0.
3951 /// \return True if the entire string was parsed (9.2), or all groups were
3952 /// parsed (10.3.5extrastuff).
3953 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3954 unsigned &Micro, bool &HadExtra) {
3957 Major = Minor = Micro = 0;
3961 if (Str.consumeInteger(10, Major))
3968 Str = Str.drop_front(1);
3970 if (Str.consumeInteger(10, Minor))
3976 Str = Str.drop_front(1);
3978 if (Str.consumeInteger(10, Micro))
3985 /// Parse digits from a string \p Str and fulfill \p Digits with
3986 /// the parsed numbers. This method assumes that the max number of
3987 /// digits to look for is equal to Digits.size().
3989 /// \return True if the entire string was parsed and there are
3990 /// no extra characters remaining at the end.
3991 bool Driver::GetReleaseVersion(StringRef Str,
3992 MutableArrayRef<unsigned> Digits) {
3996 unsigned CurDigit = 0;
3997 while (CurDigit < Digits.size()) {
3999 if (Str.consumeInteger(10, Digit))
4001 Digits[CurDigit] = Digit;
4006 Str = Str.drop_front(1);
4010 // More digits than requested, bail out...
4014 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4015 unsigned IncludedFlagsBitmask = 0;
4016 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
4018 if (Mode == CLMode) {
4019 // Include CL and Core options.
4020 IncludedFlagsBitmask |= options::CLOption;
4021 IncludedFlagsBitmask |= options::CoreOption;
4023 ExcludedFlagsBitmask |= options::CLOption;
4026 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4029 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
4030 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);