Lines Matching +full:actions +full:- +full:builder

1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
75 #include "llvm/Config/llvm-config.h"
135 return llvm::Triple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
136 : "nvptx-nvidia-cuda");
139 if (TT && (TT->getArch() == llvm::Triple::spirv32 ||
140 TT->getArch() == llvm::Triple::spirv64)) {
146 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
155 return llvm::Triple("spirv64-amd-amdhsa");
156 return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple.
161 if (TT->getArch() == llvm::Triple::amdgcn &&
162 TT->getVendor() == llvm::Triple::AMD &&
163 TT->getOS() == llvm::Triple::AMDHSA)
165 if (TT->getArch() == llvm::Triple::spirv64)
167 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
186 // On non-Windows, libclang.so/.dylib is in lib/.
187 // With a static-library build of libclang, LibClangPath will contain the
203 StringRef UseCUIDStr = A->getValue();
211 << A->getAsString(Args) << UseCUIDStr;
234 if (A->getOption().matches(options::OPT_INPUT))
236 Hasher.update(A->getAsString(Args));
259 if (!this->VFS)
260 this->VFS = llvm::vfs::getRealFileSystem();
332 if (A->getOption().hasFlag(options::Unsupported)) {
333 Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
340 // Warn about -mcpu= without an argument.
341 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
342 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
351 auto ArgString = A->getAsString(Args);
358 Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
375 if (ArgStrings[A->getIndex()] == A->getSpelling())
379 std::string ArgString = ArgStrings[A->getIndex()];
381 if (getOpts().findExact("-" + ArgString, Nearest, VisibilityMask))
383 << A->getAsString(Args) << Nearest;
397 // -{E,EP,P,M,MM} only run the preprocessor.
405 // --precompile only runs up to precompilation.
413 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
427 // -S only runs up to the backend.
431 // -c compilation only runs up to the assembler.
454 A->claim();
468 A->claim();
470 if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
474 if (A->getOption().matches(options::OPT_end_no_unused_arguments)) {
479 // Unfortunately, we have to parse some forwarding options (-Xassembler,
480 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
483 // Rewrite linker options, to replace --no-demangle with a custom internal
485 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
486 A->getOption().matches(options::OPT_Xlinker)) &&
487 A->containsValue("--no-demangle")) {
488 // Add the rewritten no-demangle argument.
489 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
492 for (StringRef Val : A->getValues())
493 if (Val != "--no-demangle")
494 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
499 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
502 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
503 A->getNumValues() > 0 &&
504 (A->getValue(0) == StringRef("-MD") ||
505 A->getValue(0) == StringRef("-MMD"))) {
506 // Rewrite to -MD/-MMD along with -MF.
507 if (A->getValue(0) == StringRef("-MD"))
508 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
510 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
511 if (A->getNumValues() == 2)
512 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
517 if (A->getOption().matches(options::OPT_l)) {
518 StringRef Value = A->getValue();
520 // Rewrite unless -nostdlib is present.
523 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
529 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
534 // Pick up inputs via the -- option.
535 if (A->getOption().matches(options::OPT__DASH_DASH)) {
536 A->claim();
537 for (StringRef Val : A->getValues())
538 DAL->append(MakeInputArg(*DAL, Opts, Val, false));
542 DAL->append(A);
547 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_S));
549 // Enforce -static if -miamcu is present.
551 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_static));
553 // Add a default value of -mlinker-version=, if one was given and the user
558 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
560 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
577 TargetTriple = A->getValue();
581 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
582 // -gnu* only, and we can not change this, so we have to detect that case as
584 if (TargetTriple.contains("-unknown-gnu") || TargetTriple.contains("-pc-gnu"))
587 // Handle Apple-specific options available here.
596 // Handle the Darwin '-arch' flag.
598 StringRef ArchName = A->getValue();
603 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
604 // '-mbig-endian'/'-EB'.
607 llvm::Triple T = A->getOption().matches(options::OPT_mlittle_endian)
616 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
640 // The `-maix[32|64]` flags are only valid for AIX targets.
644 << A->getAsString(Args) << Target.str();
646 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
653 if (A->getOption().matches(options::OPT_m64) ||
654 A->getOption().matches(options::OPT_maix64)) {
661 } else if (A->getOption().matches(options::OPT_mx32) &&
668 } else if (A->getOption().matches(options::OPT_m32) ||
669 A->getOption().matches(options::OPT_maix32)) {
675 } else if (A->getOption().matches(options::OPT_m16) &&
688 // Handle -miamcu flag.
691 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
694 if (A && !A->getOption().matches(options::OPT_m32))
696 << "-miamcu" << A->getBaseArg().getAsString(Args);
711 StringRef ABIName = A->getValue();
739 // If target is RISC-V adjust the target triple according to
748 unsigned XLen = (*ISAInfo)->getXLen();
761 // based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)?
769 StringRef LTOName = A->getValue();
778 << A->getSpelling() << A->getValue();
792 // Try to enable `-foffload-lto=full` if `-fopenmp-target-jit` is on.
799 << A->getSpelling() << "-fopenmp-target-jit";
810 RuntimeName = A->getValue();
821 << A->getSpelling() << A->getValue();
824 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
886 const llvm::Triple &HostTriple = HostTC->getTriple();
894 auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()];
910 << OMPTargetArg->getSpelling() << "HIP";
930 // the -fopenmp-targets option or used --offload-arch with OpenMP enabled.
938 // We expect that -fopenmp-targets is always used in conjunction with the
939 // option -fopenmp specifying a valid runtime with offloading support, i.e.
951 // If the user specified -fopenmp-targets= we create a toolchain for each
952 // valid triple. Otherwise, if only --offload-arch= was specified we instead
956 if (OpenMPTargets && !OpenMPTargets->getNumValues()) {
958 << OpenMPTargets->getAsString(C.getInputArgs());
961 for (StringRef T : OpenMPTargets->getValues())
968 HostTC->getTriple());
998 DerivedArchs[NVPTXTriple->getTriple()].insert(Arch);
1002 DerivedArchs[AMDTriple->getTriple()].insert(Arch);
1028 << Val << Duplicate->second;
1048 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
1069 KnownArchs[TC] = It->second;
1077 // We need to generate a SYCL toolchain if the user specified -fsycl.
1086 << IncompatArg->getSpelling() << "-fsycl";
1088 // -static-libstdc++ is not compatible with -fsycl.
1090 // -ffreestanding cannot be used with -fsycl
1146 unsigned Index = Args.MakeIndex(Opt->getSpelling());
1147 Arg *Copy = new Arg(Opt->getOption(), Args.getArgString(Index), Index);
1148 Copy->getValues() = Opt->getValues();
1149 if (Opt->isClaimed())
1150 Copy->claim();
1151 Copy->setOwnsValues(Opt->getOwnsValues());
1152 Opt->setOwnsValues(false);
1154 if (Opt->getAlias()) {
1155 const Arg *Alias = Opt->getAlias();
1156 unsigned Index = Args.MakeIndex(Alias->getSpelling());
1157 auto AliasCopy = std::make_unique<Arg>(Alias->getOption(),
1159 AliasCopy->getValues() = Alias->getValues();
1160 AliasCopy->setOwnsValues(false);
1161 if (Alias->isClaimed())
1162 AliasCopy->claim();
1163 Copy->setAlias(std::move(AliasCopy));
1176 if (Status->getType() != llvm::sys::fs::file_type::regular_file) {
1193 // An $-prefixed option should go to the tail list.
1216 A->claim();
1218 A->claim();
1247 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
1250 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
1256 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
1259 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ), CfgDir);
1278 for (auto CfgFileName : CLOptions->getAllArgValues(options::OPT_config)) {
1324 // e.g. arm64-apple-darwin23.6.0 -> arm64-apple-darwin23
1332 // e.g. arm64-apple-darwin23.6.0 -> arm64-apple-darwin
1338 // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty
1344 if (CLOptions && CLOptions->hasArg(options::OPT_no_default_config))
1350 // If name prefix is present, no --target= override was passed via CLOptions
1376 // 1. <triple>-<mode>.cfg using real driver mode
1377 // (e.g. i386-pc-linux-gnu-clang++.cfg).
1378 // 2. <triple>-<mode>.cfg using executable suffix
1379 // (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++).
1381 // (e.g. i386-pc-linux-gnu.cfg + clang++.cfg).
1383 // (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++).
1385 // Try loading <triple>-<mode>.cfg, and return if we find a match.
1388 "-" + RealMode + ".cfg"))
1395 "-" + ClangNameParts.ModeSuffix + ".cfg"))
1434 // FIXME: What are we going to do with -V and -b?
1453 if (!Opt->getOption().matches(options::OPT_config))
1456 // In CL mode, look for any pass-through arguments
1460 A->claim();
1461 CLModePassThroughArgList.push_back(A->getValue());
1466 // than clang-cl processing.
1479 if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1480 Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1485 if (!VFS->exists(IncludeDir))
1493 // -canonical-prefixes, -no-canonical-prefixes are used very early in main.
1497 // f(no-)integated-cc1 is also used very early in main.
1501 // Ignore -pipe.
1504 // Extract -ccc args.
1508 // options, either by introducing new ones or by overloading gcc ones like -V
1509 // or -b.
1513 CCCGenericGCCName = A->getValue();
1515 // Process -fproc-stat-report options.
1518 CCPrintStatReportFilename = A->getValue();
1523 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1526 // clang-cl targets MSVC-style Win32.
1536 // Build TargetTriple from target_profile option for clang-dxc.
1538 StringRef TargetProfile = A->getValue();
1545 A->claim();
1558 auto TargetInfo = ValidTargets.find(A->getValue());
1560 T.setOSName(TargetInfo->getKey());
1561 T.setArch(llvm::Triple::spirv, TargetInfo->getValue());
1564 << A->getAsString(Args) << A->getValue();
1566 A->claim();
1577 TargetTriple = A->getValue();
1579 Dir = Dir = A->getValue();
1581 A->claim();
1582 PrefixDirs.push_back(A->getValue(0));
1595 SysRoot = A->getValue();
1597 DyldPrefix = A->getValue();
1600 ResourceDir = A->getValue();
1603 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1612 if (A->getOption().matches(options::OPT_offload_host_only))
1614 else if (A->getOption().matches(options::OPT_offload_device_only))
1622 // Process -fembed-bitcode= flags.
1624 StringRef Name = A->getValue();
1632 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1640 llvm::sys::fs::remove(A->getValue());
1649 (Std->containsValue("c++20") || Std->containsValue("c++2a") ||
1650 Std->containsValue("c++23") || Std->containsValue("c++2b") ||
1651 Std->containsValue("c++26") || Std->containsValue("c++2c") ||
1652 Std->containsValue("c++latest"));
1654 // Process -fmodule-header{=} flags.
1659 if (A->getOption().matches(options::OPT_fmodule_header))
1662 StringRef ArgName = A->getValue();
1669 << A->getAsString(Args) << ArgName;
1687 return UArgs->MakeArgString(Twine("-D") + Twine(S));
1720 UArgs->hasArg(options::OPT__SLASH_arm64EC)) {
1725 // A common user mistake is specifying a target of aarch64-none-eabi or
1726 // arm-none-elf whereas the correct names are aarch64-none-elf &
1727 // arm-none-eabi. Detect these cases and issue a warning.
1738 << (TC.getTriple().getArchName().str() + "-none-eabi");
1747 << (TC.getTriple().getArchName().str() + "-none-elf");
1764 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1771 BuildInputs(C->getDefaultToolChain(), TranslatedLinkerIns, Inputs);
1778 // Construct the list of abstract actions to perform for this compilation. On
1779 // MachO targets this uses the driver-driver and universal actions.
1781 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1783 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1799 // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user
1801 while (A->getAlias())
1802 A = A->getAlias();
1803 A->render(Args, ASL);
1822 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1841 StringRef FileName = path::filename(File->path());
1844 if (fs::status(File->path(), FileStatus))
1847 llvm::MemoryBuffer::getFile(File->path());
1852 StringRef Data = CrashFile.get()->getBuffer();
1855 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1863 int OpenBracket = -1, CloseBracket = -1;
1887 CrashFilePath.assign(File->path());
1919 Level = llvm::StringSwitch<unsigned>(A->getValue())
1939 // If lld crashed, we will re-run the same command with the input it used
1963 // If lld failed, rerun it again with --reproduce.
1965 const char *TmpName = CreateTempFile(C, "linker-crash", "tar");
1971 : "--reproduce=";
1982 Report->TemporaryFiles.push_back(TmpName);
1995 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1997 } else if (!strcmp(it->second->getValue(), "-")) {
1999 << "Error generating preprocessed source(s) - "
2014 << "Error generating preprocessed source(s) - "
2019 // Don't attempt to generate preprocessed files if multiple -arch options are
2023 if (A->getOption().matches(options::OPT_arch)) {
2024 StringRef ArchName = A->getValue();
2030 << "Error generating preprocessed source(s) - cannot generate "
2031 "preprocessed source with multiple -arch options.";
2035 // Construct the list of abstract actions to perform for this compilation. On
2036 // Darwin OSes this uses the driver-driver and builds universal actions.
2077 Report->TemporaryFiles.push_back(TempFile);
2116 Report->TemporaryFiles.push_back(std::string(Script));
2128 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
2173 // Just print if -### was present.
2202 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
2219 // This is ad-hoc, but we don't want to be excessively noisy. If the result
2224 const Tool &FailingTool = FailingCommand->getCreator();
2226 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
2262 if (TC.isThreadModelSupported(A->getValue()))
2263 OS << "Thread model: " << A->getValue();
2271 // Print the build config if it's non-default.
2282 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
2301 // Make sure that Flang-only options don't pollute the Clang output
2302 // TODO: Make sure that Clang-only options don't pollute Flang output
2306 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
2311 // Parse PassedFlags by "," as all the command-line flags are passed to this
2320 // We want to show cc1-only options only when clang is invoked with -cc1 or
2321 // -Xclang.
2322 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
2327 Cur = Flags.at(Flags.size() - 1);
2330 Prev = Flags.at(Flags.size() - 2);
2350 // If the flag is in the form of "--autocomplete=-foo",
2351 // we were requested to print out all option names that start with "-foo".
2352 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
2357 // We have to query the -W flags manually as they're not in the OptTable.
2367 // case-insensitive sorting for consistency with the -help option
2368 // which prints out options in the case-insensitive alphabetical order.
2388 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
2406 // Follow gcc behavior and use stdout for --version and stderr for -v.
2442 // Print -B and COMPILER_PATH.
2497 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
2502 StringRef ProgName = A->getValue();
2513 StringRef PassedFlags = A->getValue();
2597 // Display an action graph human-readably. Action A is the "sink" node
2598 // and latest-occuring action. Traversal is in pre-order, visiting the
2604 return It->second;
2609 auto getSibIndent = [](int K) -> Twine {
2615 os << Action::getClassName(A->getKind()) << ", ";
2617 os << "\"" << IA->getInputArg().getValue() << "\"";
2619 os << '"' << BIA->getArchName() << '"' << ", {"
2620 << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
2623 OA->doOnEachDependence(
2628 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
2629 // (nvptx64-nvidia-cuda:sm_35) {#ID}
2633 os << A->getOffloadingKindPrefix();
2635 os << TC->getTriple().normalize();
2645 const ActionList *AL = &A->getInputs();
2647 if (AL->size()) {
2660 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
2664 auto S = A->getOffloadingKindPrefix();
2667 if (A->getOffloadingArch())
2668 offload_os << ", " << A->getOffloadingArch();
2673 auto getSelfIndent = [](int K) -> Twine {
2674 return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
2680 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
2686 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
2694 /// assembly actions.
2700 return llvm::any_of(A->inputs(), ContainsCompileOrAssembleAction);
2706 ActionList &Actions = C.getActions();
2707 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
2713 if (A->getOption().matches(options::OPT_arch)) {
2717 tools::darwin::getArchTypeForMachOArchName(A->getValue());
2719 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
2723 A->claim();
2724 if (ArchNames.insert(A->getValue()).second)
2725 Archs.push_back(A->getValue());
2730 // the architecture (to the default) so that -Xarch_ is handled correctly.
2744 // -save-temps. Compatibility wins for now.
2746 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
2748 << types::getTypeName(Act->getType());
2755 // so that -Xarch_ gets overwritten.
2756 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2757 Actions.append(Inputs.begin(), Inputs.end());
2759 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2763 bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2764 !A->getOption().matches(options::OPT_gstabs);
2766 ContainsCompileOrAssembleAction(Actions.back())) {
2772 if (Act->getType() == types::TY_Image) {
2774 Inputs.push_back(Actions.back());
2775 Actions.pop_back();
2776 Actions.push_back(
2782 Action* LastAction = Actions.back();
2783 Actions.pop_back();
2784 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2797 if (Value == "-")
2803 // allow the user to put "-fmodule-header -xc++-header vector" for example.
2825 // In CL mode, don't error on apparently non-existent linker inputs, because
2829 // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver
2832 // look in the registry might move into lld-link in the future so that
2833 // lld-link invocations in non-MSVC shells just work too.)
2834 // - `clang-cl ... /link ...` can pass arbitrary flags to the linker,
2838 // "'linker' input unused [-Wunused-command-line-argument]" warning instead
2844 // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the
2852 // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o
2855 // `clang /GR-` compiles without error to see if the compiler is cl.exe,
2856 // so we can't downgrade diagnostics for `/GR-` from an error to a warning
2885 // Track the current user specified (-x) input. We also explicitly track the
2887 // actually use it, so we warn about unused -x arguments.
2895 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2905 << Previous->getSpelling() << A->getSpelling();
2914 // Warn -x after last input file has no effect
2919 LastInputArg->getIndex() < LastXArg->getIndex())
2920 Diag(clang::diag::warn_drv_unused_x) << LastXArg->getValue();
2924 if (A->getOption().getKind() == Option::InputClass) {
2925 const char *Value = A->getValue();
2932 InputTypeArg->claim();
2935 if (memcmp(Value, "-", 2) == 0) {
2941 // If running with -E, treat as a C input (this changes the
2942 // builtin macros, for example). This may be overridden by -ObjC
2956 // clang-cl /E, or Object otherwise.
2984 // If running with -fthinlto-index=, extensions that normally identify
2991 // -ObjC and -ObjC++ override the default language, but only for "source
3005 // C headers by default - we know we are in C++ mode and we do not
3012 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
3021 InputTypeArg->claim();
3032 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
3033 StringRef Value = A->getValue();
3036 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
3039 A->claim();
3040 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
3041 StringRef Value = A->getValue();
3044 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
3047 A->claim();
3048 } else if (A->getOption().hasFlag(options::LinkerInput)) {
3053 } else if (A->getOption().matches(options::OPT_x)) {
3055 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
3056 A->claim();
3058 // Follow gcc behavior and treat as linker input for invalid -x
3062 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
3066 // If the user has put -fmodule-header{,=} then we treat C++ headers as
3067 // header unit inputs. So we 'promote' -xc++-header appropriately.
3070 } else if (A->getOption().getID() == options::OPT_U) {
3071 assert(A->getNumValues() == 1 && "The /U option has one value.");
3072 StringRef Val = A->getValue(0);
3083 Arg *A = MakeInputArg(Args, Opts, "-");
3090 /// the required device actions.
3092 /// Flag used to trace errors in the builder.
3095 /// The compilation that is using this builder.
3104 /// Builder interface. It doesn't build anything or keep any state.
3110 // The builder acted successfully on the current action.
3112 // The builder didn't have to act on the current action.
3114 // The builder was successful and requested the host action to not be
3120 /// Compilation associated with this builder.
3123 /// Tool chains associated with this builder. The same programming
3127 /// The derived arguments associated with this builder.
3130 /// The inputs associated with this builder.
3160 /// Append top level actions generated by the builder.
3163 /// Append linker device actions generated by the builder.
3166 /// Append linker host action generated by the builder.
3169 /// Append linker actions generated by the builder.
3172 /// Initialize the builder. Return true if any initialization errors are
3176 /// Return true if the builder can use bundling/unbundling.
3179 /// Return true if this builder is valid. We have a valid builder if we have
3189 /// Base class for CUDA/HIP action builder. It injects device code in
3193 /// Flags to signal if the user requested host-only or device-only
3215 /// The CUDA actions for the current input.
3221 /// Flag that is set to true if this builder acted on the current input.
3224 /// Flag for -fgpu-rdc.
3230 /// Compilation unit ID specified by option '-fuse-cuid=' or'-cuid='.
3247 // to trigger the creation of all the CUDA device actions.
3250 // architecture. If we are in host-only mode we return 'success' so that
3258 if (!(IA->getType() == types::TY_CUDA ||
3259 IA->getType() == types::TY_HIP ||
3260 IA->getType() == types::TY_PP_HIP)) {
3261 // The builder will ignore this input.
3266 // Set the flag to true, so that the builder acts on the current input.
3270 IA->setId(CUIDOpts.getCUID(IA->getInputArg().getValue(), Args));
3276 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
3280 C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId()));
3289 // If -fgpu-rdc is disabled, should not unbundle since there is no
3291 if (UA->getType() == types::TY_Object && !Relocatable)
3295 auto *IA = cast<InputAction>(UA->getInputs().back());
3296 std::string FileName = IA->getInputArg().getAsString(Args);
3303 if (IA->getType() == types::TY_Object &&
3313 UA->registerDependentActionInfo(ToolChains[0], Arch,
3324 // Utility to append actions to the top level list.
3328 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
3342 // If we have CUDA actions at this point, that's because we have a have
3378 if (HostTC->getTriple().isNVPTX() ||
3379 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
3382 // asserts that assume device-side compilation.
3384 << HostTC->getTriple().getArchName();
3397 // --offload and --offload-arch options are mutually exclusive.
3401 C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch"
3402 << "--offload";
3409 if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
3410 A->getOption().matches(options::OPT_no_offload_arch_EQ)))
3412 A->claim();
3414 for (StringRef ArchStr : llvm::split(A->getValue(), ",")) {
3415 if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
3420 auto GPUsOrErr = ToolChains.front()->getSystemGPUArchs(Args);
3424 << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
3435 } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
3437 else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
3448 << ConflictingArchs->first << ConflictingArchs->second;
3461 if (ToolChains.front()->getTriple().isSPIRV()) {
3462 if (ToolChains.front()->getTriple().getVendor() == llvm::Triple::AMD)
3475 /// \brief CUDA action builder. It injects device code in the host backend
3507 // If we don't have more CUDA actions, we don't have any dependences to
3515 "Not expecting CUDA actions in host-only compilation.");
3522 // device-only mode.
3545 // device-only mode.
3551 assert(AssembleAction->getType() == types::TY_Object);
3552 assert(AssembleAction->getInputs().size() == 1);
3554 Action *BackendAction = AssembleAction->getInputs()[0];
3555 assert(BackendAction->getType() == types::TY_PP_Asm);
3561 C.MakeAction<OffloadAction>(DDep, A->getType()));
3565 // We generate the fat binary if we have device input actions.
3578 // Remove the CUDA actions as they are already connected to an host
3583 // We avoid creating host action in device-only mode.
3588 // top-level action.
3603 /// \brief HIP action builder. It injects device code in the host backend
3609 // BundleOutput needs to be tri-value: None, true, or false.
3610 // Bundle code objects except --no-gpu-output is specified for device
3612 // --gpu-bundle-output is specified for device only compilation.
3631 << "-fhip-emit-relocatable"
3632 << "-fgpu-rdc";
3637 << "-fhip-emit-relocatable"
3638 << "--cuda-device-only";
3658 ? llvm::Triple("spirv64-amd-amdhsa")
3685 // non-relocatable device code, where we generate fat binary for device
3694 "Not expecting HIP actions in host-only compilation.");
3720 if (ToolChains.front()->getTriple().isSPIRV()) {
3721 // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain
3722 // (HIPSPVToolChain) runs post-link LLVM IR passes.
3752 DDep, CudaDeviceActions[I]->getType());
3768 // Remove the CUDA actions as they are already connected to an host
3779 // Later on, device actions in DeviceLinkerInputs are used to create
3780 // device link actions in appendLinkDependences and the created device
3781 // link actions are passed to the offload action as device dependence.
3785 LI->push_back(A);
3807 DDep, CudaDeviceActions[I]->getType());
3828 ActionList Actions;
3844 Actions.push_back(C.MakeAction<OffloadAction>(
3845 DeviceLinkDeps, DeviceLinkAction->getType()));
3852 AL.append(Actions);
3857 // in a fat binary for mixed host-device compilation. For device-only
3862 Actions,
3868 C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
3870 AL.append(Actions);
3883 /// Specialized builders being used by this offloading action builder.
3893 // Create a specialized builder for each device toolchain.
3897 // Create a specialized builder for CUDA.
3900 // Create a specialized builder for HIP.
3912 IsValid = IsValid && !SB->initialize();
3914 // Update the counters if the builder is valid.
3915 if (SB->isValid()) {
3917 if (SB->canUseBundlerUnbundler())
3935 assert(Loc->second == InputArg &&
3941 /// If no device dependence actions exist, just return the host action \a
3942 /// HostAction. If an error is found or if no builder requires the host action
3964 if (!SB->isValid()) {
3969 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3971 // If the builder explicitly says the host action should be ignored,
3977 // Unless the builder was inactive for this action, we have to record the
3980 OffloadKind |= SB->getAssociatedOffloadKind();
4001 /// results will be kept in this action builder. Return true if an error was
4011 // input action of non-source file, we replace the host action by the
4017 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
4018 (!types::isSrcFile(HostAction->getType()) ||
4019 HostAction->getType() == types::TY_PP_HIP)) {
4022 UnbundlingHostAction->registerDependentActionInfo(
4034 if (!SB->isValid())
4037 auto RetCode = SB->addDeviceDependences(HostAction);
4039 // Host dependences for device actions are not compatible with that same
4044 // Unless the builder was inactive for this action, we have to record the
4047 OffloadKind |= SB->getAssociatedOffloadKind();
4053 HostAction = UA->getInputs().back();
4058 /// Add the offloading top level actions to the provided action list. This
4066 // Get the device actions to be appended.
4069 if (!SB->isValid())
4071 SB->appendTopLevelActions(OffloadAL);
4075 // the resulting list. Otherwise, just append the device actions. For
4079 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
4095 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
4102 if (!SB->isValid())
4104 SB->appendLinkDeviceActions(AL);
4109 // Build a list of device linking actions.
4115 // Let builders add host linking actions.
4118 if (!SB->isValid())
4120 HA = SB->appendLinkHostActions(DeviceAL);
4124 HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(),
4135 // Add all the dependences from the device linking actions.
4138 if (!SB->isValid())
4141 SB->appendLinkDependences(DDeps);
4153 // is a link action it is assumed to depend on all actions generated so
4155 HostAction->setHostOffloadInfo(ActiveOffloadKinds,
4159 for (auto *A : HostAction->inputs()) {
4163 auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second);
4166 A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr);
4184 ActionList &Actions) const {
4189 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
4219 // If -dumpdir is not specified, give a default prefix derived from the link
4220 // output filename. For example, `clang -g -gsplit-dwarf a.c -o x` passes
4221 // `-dumpdir x-` to cc1. If -o is unspecified, use
4228 (FinalOutput ? FinalOutput->getValue()
4230 "-"));
4231 Arg->claim();
4237 // If only preprocessing or /Y- is used, all pch handling is disabled.
4238 // Rather than check for it everywhere, just remove clang-cl pch-related
4259 if (InputArg->isClaimed())
4263 InputArg->claim();
4265 // Suppress all unused style warnings with -Qunused-arguments
4270 // by a command-line argument with a corresponding Arg.
4273 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
4274 // Special case '-E' warning on a previously preprocessed file to make
4283 << InputArg->getAsString(Args) << !!FinalPhaseArg
4284 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
4287 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
4289 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
4302 Actions.push_back(ClangClPch);
4320 const InputList &Inputs, ActionList &Actions) const {
4321 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
4330 StringRef V = A->getValue();
4335 << A->getSpelling() << V;
4342 StringRef V = A->getValue();
4347 << A->getSpelling() << V;
4354 if (A->getValue()[0] == '\0') {
4356 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
4361 handleArguments(C, Args, Inputs, Actions);
4372 // Builder to be used to build offloading actions.
4378 // Construct the actions to perform.
4398 CUID = CUIDOpts.getCUID(InputArg->getValue(), Args);
4399 cast<InputAction>(Current)->setId(CUID);
4402 // Use the current host action in any of the offloading actions, if
4405 if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg))
4412 Current = OffloadBuilder->addDeviceDependencesToHostAction(
4442 ExtractAPIAction->addHeaderInput(Current);
4448 // later actions in the same command line?
4462 // Try to build the offloading actions and add the result as a dependency
4466 // Use the current host action in any of the offloading actions, if
4468 else if (OffloadBuilder->addHostDependenceToDeviceActions(Current,
4472 if (Current->getType() == types::TY_Nothing)
4478 Actions.push_back(Current);
4480 // Add any top level actions generated for offloading.
4482 OffloadBuilder->appendTopLevelActions(Actions, Current, InputArg);
4484 Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4494 OffloadBuilder->appendDeviceLinkActions(Actions);
4499 if (Action *Wrapper = OffloadBuilder->makeHostLinkAction())
4508 LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4514 LA = OffloadBuilder->processHostLinkAction(LA);
4515 Actions.push_back(LA);
4520 Actions.push_back(
4549 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
4570 Actions.push_back(Current);
4575 Actions.push_back(
4582 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a
4585 // If either --print-supported-extensions or --print-enabled-extensions is
4594 << "--print-supported-extensions";
4601 << "--print-enabled-extensions";
4605 // Use the -mcpu=? flag as the dummy input to cc1.
4606 Actions.clear();
4609 Actions.push_back(
4612 I.second->claim();
4616 // Call validator for dxil when -Vd not in Args.
4622 Action *LastAction = Actions.back();
4623 Actions.push_back(C.MakeAction<BinaryAnalyzeJobAction>(
4628 // Claim ignored clang-cl options.
4696 // --offload and --offload-arch options are mutually exclusive.
4701 << "--offload"
4703 ? "--offload-arch"
4704 : "--no-offload-arch");
4712 // Extract any '--[no-]offload-arch' arguments intended for this toolchain.
4714 if (Arg->getOption().matches(options::OPT_Xopenmp_target_EQ) &&
4715 ToolChain::getOpenMPTriple(Arg->getValue(0)) == TC->getTriple()) {
4716 Arg->claim();
4717 unsigned Index = Args.getBaseArgs().MakeIndex(Arg->getValue(1));
4721 TC->getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
4722 << Arg->getAsString(Args);
4730 if (Arg->getOption().matches(options::OPT_offload_arch_EQ)) {
4731 for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4733 auto GPUsOrErr = TC->getSystemGPUArchs(Args);
4738 TC->getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
4739 << llvm::Triple::getArchTypeName(TC->getArch())
4740 << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
4747 TC->getTriple(), SuppressError));
4751 C, Args, Arch, TC->getTriple(), SuppressError);
4757 } else if (Arg->getOption().matches(options::OPT_no_offload_arch_EQ)) {
4758 for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4763 C, Args, Arch, TC->getTriple(), SuppressError);
4773 getConflictOffloadArchCombination(Archs, TC->getTriple())) {
4775 << ConflictingArchs->first << ConflictingArchs->second;
4804 // Don't build offloading actions if explicitly disabled or we do not have a
4824 ToolChains.push_back(TI->second);
4856 HostAction->getType() != types::TY_Nothing &&
4858 ->getTriple()
4860 HostAction->setCannotBeCollapsedWithNextDependentAction();
4870 // Assemble actions are not used for the SYCL device side. Both compile
4871 // and backend actions are used to generate IR and textual IR if needed.
4877 if (A->getType() == types::TY_Nothing)
4881 A->propagateDeviceOffloadInfo(Kind, TCAndArch->second.data(),
4882 TCAndArch->first);
4887 HostAction->getType() != types::TY_Nothing) {
4890 // collapsed with any other actions so we can use it in the device.
4891 HostAction->setCannotBeCollapsedWithNextDependentAction();
4894 TCAndArch->second.data(), Kind);
4896 DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4904 // Compiling HIP in non-RDC mode requires linking each action individually.
4906 if ((A->getType() != types::TY_Object &&
4907 A->getType() != types::TY_LTO_BC) ||
4917 DDeps.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4919 DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4921 // Compiling CUDA in non-RDC mode uses the PTX output if available.
4922 for (Action *Input : A->getInputs())
4923 if (Kind == Action::OFK_Cuda && A->getType() == types::TY_Object &&
4926 DDep.add(*Input, *TCAndArch->first, TCAndArch->second.data(), Kind);
4927 OffloadActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType()));
4933 // HIP code in non-RDC mode will bundle the output if it invoked the linker.
4940 [](Action *A) { return A->getType() != types::TY_Image; });
4942 // All kinds exit now in device-only mode except for non-RDC mode HIP.
4952 // If we are not in RDC-mode we just emit the final CUDA fatbinary for
4961 // If we are not in RDC-mode we just emit the final HIP fatbinary for each
4968 // Package all the offloading actions into a single output that can be
4976 // HIP wants '--offload-device-only' to create a fatbinary by default.
4983 return A->getType() == types::TY_Nothing;
4994 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
4996 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
4999 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
5002 // Use of --sycl-link will only allow for the link phase to occur. This is
5015 // -M and -MM specify the dependency file name by altering the output type,
5016 // -if -MD and -MMD are not specified.
5021 OutputTy = Input->getType();
5042 // With 'fexperimental-modules-reduced-bmi', we don't want to run the
5043 // precompile phase unless the user specified '--precompile'. In the case
5044 // the '--precompile' flag is enabled, we will try to emit the reduced BMI
5050 types::ID OutputTy = getPrecompiledType(Input->getType());
5059 ModName = A->getValue();
5114 (((Input->getOffloadingToolChain() &&
5115 Input->getOffloadingToolChain()->getTriple().isAMDGPU()) ||
5146 // It is an error to provide a -o option if we are making multiple output
5155 // and -c is passed, we still want to be able to generate a .ifs file while
5159 // OffloadClass of type TY_Nothing: device-only output will place many outputs
5161 // as outputs. Also ignore device-only outputs if we're compiling with
5162 // -fsyntax-only.
5167 if (A->getType() != types::TY_Nothing &&
5168 A->getType() != types::TY_DX_CONTAINER &&
5169 !(A->getKind() == Action::IfsMergeJobClass ||
5170 (A->getType() == clang::driver::types::TY_IFS_CPP &&
5171 A->getKind() == clang::driver::Action::CompileJobClass &&
5173 (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
5174 A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
5176 else if (A->getKind() == Action::OffloadClass &&
5177 A->getType() == types::TY_Nothing &&
5179 NumOutputs += A->size();
5194 if (A->getOption().matches(options::OPT_arch))
5195 ArchNames.insert(A->getValue());
5201 // -arch_multiple and -final_output <final image name>. Unfortunately, this
5209 LinkingOutput = FinalOutput->getValue();
5222 // If we have more than one job, then disable integrated-cc1 for now. Do this
5237 LinkingOutput = FinalOutput->getValue();
5249 << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
5251 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
5252 << ", mem=" << ProcStat->PeakMemory << " Kb\n";
5261 Out << ',' << ProcStat->TotalTime.count() << ','
5262 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
5284 // If the user passed -Qunused-arguments or there were errors, don't warn
5290 // Claim -fdriver-only here.
5292 // Claim -### here.
5295 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
5309 if (!A->isClaimed()) {
5310 if (A->getOption().hasFlag(options::NoArgumentUnused))
5315 const Option &Opt = A->getOption();
5320 if (AA->isClaimed()) {
5330 // In clang-cl, don't mention unknown arguments here since they have
5332 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) {
5333 if (A->getOption().hasFlag(options::TargetSpecific) &&
5334 !A->isIgnoredTargetSpecific() && !HasAssembleJob &&
5335 // When for example -### or -v is used
5341 << A->getSpelling() << getTargetTriple();
5344 << A->getAsString(C.getArgs());
5352 /// Utility class to control the collapse of dependent actions and select the
5364 /// Set to true if the current toolchain refers to host actions.
5367 /// Set to true if save-temps and embed-bitcode functionalities are active.
5383 !CurAction->isCollapsingWithNextDependentActionLegal())
5390 // only with other device actions. Otherwise, we would do the same but
5391 // with host actions only.
5393 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
5395 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
5397 !CurAction->isCollapsingWithNextDependentActionLegal())
5402 } else if (OA->hasHostDependence()) {
5403 CurAction = OA->getHostDependence();
5405 !CurAction->isCollapsingWithNextDependentActionLegal())
5432 /// Struct that relates an action with the offload actions that would be
5437 /// The offload actions we need to take care off if this action is
5442 /// Append collapsed offload actions from the give nnumber of elements in the
5459 /// - Assemble + Backend + Compile;
5460 /// - Assemble + Backend ;
5461 /// - Backend + Compile.
5481 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
5482 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
5485 // When using -fembed-bitcode, it is required to have the same tool (clang)
5493 if (!T->hasIntegratedAssembler())
5496 Inputs = CJ->getInputs();
5516 if (!T->hasIntegratedAssembler())
5519 Inputs = BJ->getInputs();
5537 // -save-temps. I.e. there is no need for a separate compile job just to
5541 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
5542 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
5556 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
5557 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
5560 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
5563 Inputs = CJ->getInputs();
5571 /// action. If combining results in the collapse of offloading actions, those
5575 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
5592 NewInputs.append(PJ->input_begin(), PJ->input_end());
5603 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
5606 /// Check if a chain of actions can be combined and return the tool that can
5607 /// handle the combination of actions. The pointer to the current inputs \a
5608 /// Inputs and the list of offload actions \a CollapsedOffloadActions
5609 /// connected to collapsed actions are updated accordingly. The latter enables
5615 // Get the largest chain of actions that we could combine.
5629 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
5636 // Attempt to combine actions. If all combining attempts failed, just return
5648 Inputs = BaseAction->getInputs();
5659 /// is not necessarily represented in the toolchain's triple -- for example,
5660 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
5666 std::string TriplePlusArch = TC->getTriple().normalize();
5668 TriplePlusArch += "-";
5671 TriplePlusArch += "-";
5686 return CachedResult->second;
5703 if (A->getOption().matches(options::OPT_ftime_trace_EQ)) {
5704 Path = A->getValue();
5714 Path = DumpDir->getValue();
5746 // Host Action 1 -> OffloadAction -> Host Action 2
5749 // Device Action 1 -> OffloadAction -> Device Action 2
5754 // Host Action 1 ---> OffloadAction -> Host Action 2
5759 // Device Action 1 ---> OffloadAction -> Device Action 2
5768 if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
5770 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
5775 DepA->getOffloadingDeviceKind()));
5783 // dependence. The dependences can't therefore be a top-level action.
5784 OA->doOnEachDependence(
5790 DepA->getOffloadingDeviceKind()));
5794 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
5795 : OA->getHostDependence();
5800 OA->getHostDependence(),
5804 InputInfoList Inputs = It->second;
5813 const Arg &Input = IA->getInputArg();
5824 StringRef ArchName = BAA->getArchName();
5833 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
5839 ActionList Inputs = A->getInputs();
5852 // need to build jobs for host/device-side inputs it may have held.
5854 cast<OffloadAction>(OA)->doOnEachDependence(
5860 DepA->getOffloadingDeviceKind()));
5866 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
5873 CachedResults, A->getOffloadingDeviceKind()));
5885 // ... except dsymutil actions, which use their actual input as the base
5887 if (JA->getType() == types::TY_dSYM)
5897 const ToolChain &ToolTC = T->getToolChain();
5899 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
5914 // outputs. We also update the results cache so that other actions using
5916 for (auto &UI : UA->getDependentActionsInfo()) {
5920 // Unbundling actions are never at the top level. When we generate the
5926 UI.DependentToolChain->getTriple().normalize(),
5962 } else if (JA->getType() == types::TY_Nothing)
5965 // We only have to generate a prefix for the host if this is not a top-level
5968 A->getOffloadingDeviceKind(), EffectiveTriple.normalize(),
5970 !(A->getOffloadingHostActiveKinds() == Action::OFK_None ||
5976 if (T->canEmitIR() && OffloadingPrefix.empty())
5981 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
5982 << " - \"" << T->getName() << "\", inputs: [";
6001 T->ConstructJob(C, *JA, Result, InputInfos, Args, LinkingOutput);
6003 T->ConstructJobMultipleOutputs(C, *JA, UnbundlingResults, InputInfos,
6066 ? std::string(A->getValue())
6073 const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%";
6084 Twine(Prefix) + "-" + BoundArch + "." + Suffix);
6087 GetTemporaryPath((Twine(Prefix) + "-" + BoundArch).str(), Suffix);
6098 // with the `-fmodule-output` option or `-fmodule-output=` option specified.
6100 // - If `-fmodule-output=` is specfied, then the module file is
6102 // - Otherwise if the output object file of the module unit is specified, the
6105 // the corresponding suffix. This requires both `-o` and `-c` are specified.
6106 // - Otherwise, the output path of the module file will be the same with the
6136 return C.addResultFile(FinalOutput->getValue(), &JA);
6145 NameArg = A->getValue();
6153 return "-";
6158 return "-";
6198 return "-";
6207 // `-fmodule-output`.
6222 // The non-offloading toolchain on Darwin requires deterministic input
6238 // Dsymutil actions should use the full path.
6240 ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
6242 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
6262 ->getValue();
6272 ->getValue();
6277 // clang-cl uses BaseName for the executable name.
6282 // HIP image for device compilation with -fno-gpu-rdc is per compilation
6294 Output += "-";
6308 ->getValue();
6322 Suffixed += "-";
6325 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
6330 // The relocatable compilation in HIP and OpenMP implies -emit-llvm.
6339 TC->getTriple().isAMDGPU()));
6350 // Prepend object file path if -save-temps=obj
6354 SmallString<128> TempPath(FinalOutput->getValue());
6396 -> std::optional<std::string> {
6397 // Respect a limited subset of the '-Bprefix' functionality in GCC by
6446 Names.emplace_back((TargetTriple + "-" + Tool).str());
6462 // Respect a limited subset of the '-Bprefix' functionality in GCC by
6483 // E.g. <triple>-gcc on the path will be found instead
6506 auto evaluate = [&](const char *library) -> std::optional<std::string> {
6510 // to look at the command-line arguments for the proper json. These
6518 // return "libc++.modules-asan.json";
6538 auto evaluate = [&](const char *library) -> std::optional<std::string> {
6588 Output = FpArg->getValue();
6596 Output = YcArg->getValue();
6839 !types::isAcceptedByClang((*JA.input_begin())->getType()))
6854 !types::isAcceptedByFlang((*JA.input_begin())->getType()))
6872 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
6955 return "clang-cpp";
6957 return "clang-cl";
6961 return "clang-dxc";
6972 // -fsave-optimization-record enables it.
6977 // -fsave-optimization-record=<format> enables it as well.
6982 // -foptimization-record-file alone enables it too.
6987 // -foptimization-record-passes alone enables it too.
7017 // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
7019 // have to manually search for a --driver-mode=cl argument the hard way.
7020 // Finally, our -cc1 tools don't care which tokenization mode we use because
7024 if (strcmp(F, "--rsp-quoting=posix") == 0)
7026 else if (strcmp(F, "--rsp-quoting=windows") == 0)
7031 // files end-of-lines. We only use this for the /LINK driver argument with
7032 // clang-cl.exe on Windows.
7041 if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).starts_with("-cc1"))
7052 // If -cc1 came from a response file, remove the EOL sentinels.
7055 if (FirstArg != Args.end() && StringRef(*FirstArg).starts_with("-cc1")) {
7056 // If -cc1 came from a response file, remove the EOL sentinels.
7059 Args.resize(newEnd - Args.begin());
7067 return SavedStrings.insert(S).first->getKeyData();
7090 /// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
7093 /// \param OS - The stream to write edit information to.
7094 /// \param Args - The vector of command line arguments.
7095 /// \param Edit - The override command to perform.
7096 /// \param SavedStrings - Set to use for storing string representations.
7112 Edit.slice(2, Edit.size() - 1).contains('/')) {
7115 ReplPattern = ReplPattern.slice(0, ReplPattern.size() - 1);
7118 // Ignore end-of-line response file markers
7147 // Ignore end-of-line response file markers
7150 if (A[0] == '-' && A[1] == 'O' &&
7159 Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));