xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Driver/ToolChains/Cuda.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===--- Cuda.cpp - Cuda Tool and ToolChain Implementations -----*- C++ -*-===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg 
97330f729Sjoerg #include "Cuda.h"
107330f729Sjoerg #include "CommonArgs.h"
117330f729Sjoerg #include "InputInfo.h"
127330f729Sjoerg #include "clang/Basic/Cuda.h"
137330f729Sjoerg #include "clang/Config/config.h"
147330f729Sjoerg #include "clang/Driver/Compilation.h"
157330f729Sjoerg #include "clang/Driver/Distro.h"
167330f729Sjoerg #include "clang/Driver/Driver.h"
177330f729Sjoerg #include "clang/Driver/DriverDiagnostic.h"
187330f729Sjoerg #include "clang/Driver/Options.h"
19*e038c9c4Sjoerg #include "llvm/ADT/Optional.h"
207330f729Sjoerg #include "llvm/Option/ArgList.h"
217330f729Sjoerg #include "llvm/Support/FileSystem.h"
22*e038c9c4Sjoerg #include "llvm/Support/Host.h"
237330f729Sjoerg #include "llvm/Support/Path.h"
247330f729Sjoerg #include "llvm/Support/Process.h"
257330f729Sjoerg #include "llvm/Support/Program.h"
26*e038c9c4Sjoerg #include "llvm/Support/TargetParser.h"
277330f729Sjoerg #include "llvm/Support/VirtualFileSystem.h"
287330f729Sjoerg #include <system_error>
297330f729Sjoerg 
307330f729Sjoerg using namespace clang::driver;
317330f729Sjoerg using namespace clang::driver::toolchains;
327330f729Sjoerg using namespace clang::driver::tools;
337330f729Sjoerg using namespace clang;
347330f729Sjoerg using namespace llvm::opt;
357330f729Sjoerg 
36*e038c9c4Sjoerg namespace {
37*e038c9c4Sjoerg struct CudaVersionInfo {
38*e038c9c4Sjoerg   std::string DetectedVersion;
39*e038c9c4Sjoerg   CudaVersion Version;
40*e038c9c4Sjoerg };
417330f729Sjoerg // Parses the contents of version.txt in an CUDA installation.  It should
427330f729Sjoerg // contain one line of the from e.g. "CUDA Version 7.5.2".
parseCudaVersionFile(llvm::StringRef V)43*e038c9c4Sjoerg CudaVersionInfo parseCudaVersionFile(llvm::StringRef V) {
44*e038c9c4Sjoerg   V = V.trim();
457330f729Sjoerg   if (!V.startswith("CUDA Version "))
46*e038c9c4Sjoerg     return {V.str(), CudaVersion::UNKNOWN};
477330f729Sjoerg   V = V.substr(strlen("CUDA Version "));
48*e038c9c4Sjoerg   SmallVector<StringRef,4> VersionParts;
49*e038c9c4Sjoerg   V.split(VersionParts, '.');
50*e038c9c4Sjoerg   return {"version.txt: " + V.str() + ".",
51*e038c9c4Sjoerg           VersionParts.size() < 2
52*e038c9c4Sjoerg               ? CudaVersion::UNKNOWN
53*e038c9c4Sjoerg               : CudaStringToVersion(
54*e038c9c4Sjoerg                     join_items(".", VersionParts[0], VersionParts[1]))};
557330f729Sjoerg }
56*e038c9c4Sjoerg 
getCudaVersion(uint32_t raw_version)57*e038c9c4Sjoerg CudaVersion getCudaVersion(uint32_t raw_version) {
58*e038c9c4Sjoerg   if (raw_version < 7050)
59*e038c9c4Sjoerg     return CudaVersion::CUDA_70;
60*e038c9c4Sjoerg   if (raw_version < 8000)
617330f729Sjoerg     return CudaVersion::CUDA_75;
62*e038c9c4Sjoerg   if (raw_version < 9000)
637330f729Sjoerg     return CudaVersion::CUDA_80;
64*e038c9c4Sjoerg   if (raw_version < 9010)
657330f729Sjoerg     return CudaVersion::CUDA_90;
66*e038c9c4Sjoerg   if (raw_version < 9020)
677330f729Sjoerg     return CudaVersion::CUDA_91;
68*e038c9c4Sjoerg   if (raw_version < 10000)
697330f729Sjoerg     return CudaVersion::CUDA_92;
70*e038c9c4Sjoerg   if (raw_version < 10010)
717330f729Sjoerg     return CudaVersion::CUDA_100;
72*e038c9c4Sjoerg   if (raw_version < 10020)
737330f729Sjoerg     return CudaVersion::CUDA_101;
74*e038c9c4Sjoerg   if (raw_version < 11000)
75*e038c9c4Sjoerg     return CudaVersion::CUDA_102;
76*e038c9c4Sjoerg   if (raw_version < 11010)
77*e038c9c4Sjoerg     return CudaVersion::CUDA_110;
78*e038c9c4Sjoerg   if (raw_version < 11020)
79*e038c9c4Sjoerg     return CudaVersion::CUDA_111;
80*e038c9c4Sjoerg   return CudaVersion::LATEST;
81*e038c9c4Sjoerg }
82*e038c9c4Sjoerg 
parseCudaHFile(llvm::StringRef Input)83*e038c9c4Sjoerg CudaVersionInfo parseCudaHFile(llvm::StringRef Input) {
84*e038c9c4Sjoerg   // Helper lambda which skips the words if the line starts with them or returns
85*e038c9c4Sjoerg   // None otherwise.
86*e038c9c4Sjoerg   auto StartsWithWords =
87*e038c9c4Sjoerg       [](llvm::StringRef Line,
88*e038c9c4Sjoerg          const SmallVector<StringRef, 3> words) -> llvm::Optional<StringRef> {
89*e038c9c4Sjoerg     for (StringRef word : words) {
90*e038c9c4Sjoerg       if (!Line.consume_front(word))
91*e038c9c4Sjoerg         return {};
92*e038c9c4Sjoerg       Line = Line.ltrim();
93*e038c9c4Sjoerg     }
94*e038c9c4Sjoerg     return Line;
95*e038c9c4Sjoerg   };
96*e038c9c4Sjoerg 
97*e038c9c4Sjoerg   Input = Input.ltrim();
98*e038c9c4Sjoerg   while (!Input.empty()) {
99*e038c9c4Sjoerg     if (auto Line =
100*e038c9c4Sjoerg             StartsWithWords(Input.ltrim(), {"#", "define", "CUDA_VERSION"})) {
101*e038c9c4Sjoerg       uint32_t RawVersion;
102*e038c9c4Sjoerg       Line->consumeInteger(10, RawVersion);
103*e038c9c4Sjoerg       return {"cuda.h: CUDA_VERSION=" + Twine(RawVersion).str() + ".",
104*e038c9c4Sjoerg               getCudaVersion(RawVersion)};
105*e038c9c4Sjoerg     }
106*e038c9c4Sjoerg     // Find next non-empty line.
107*e038c9c4Sjoerg     Input = Input.drop_front(Input.find_first_of("\n\r")).ltrim();
108*e038c9c4Sjoerg   }
109*e038c9c4Sjoerg   return {"cuda.h: CUDA_VERSION not found.", CudaVersion::UNKNOWN};
110*e038c9c4Sjoerg }
111*e038c9c4Sjoerg } // namespace
112*e038c9c4Sjoerg 
WarnIfUnsupportedVersion()113*e038c9c4Sjoerg void CudaInstallationDetector::WarnIfUnsupportedVersion() {
114*e038c9c4Sjoerg   if (DetectedVersionIsNotSupported)
115*e038c9c4Sjoerg     D.Diag(diag::warn_drv_unknown_cuda_version)
116*e038c9c4Sjoerg         << DetectedVersion
117*e038c9c4Sjoerg         << CudaVersionToString(CudaVersion::LATEST_SUPPORTED);
1187330f729Sjoerg }
1197330f729Sjoerg 
CudaInstallationDetector(const Driver & D,const llvm::Triple & HostTriple,const llvm::opt::ArgList & Args)1207330f729Sjoerg CudaInstallationDetector::CudaInstallationDetector(
1217330f729Sjoerg     const Driver &D, const llvm::Triple &HostTriple,
1227330f729Sjoerg     const llvm::opt::ArgList &Args)
1237330f729Sjoerg     : D(D) {
1247330f729Sjoerg   struct Candidate {
1257330f729Sjoerg     std::string Path;
1267330f729Sjoerg     bool StrictChecking;
1277330f729Sjoerg 
1287330f729Sjoerg     Candidate(std::string Path, bool StrictChecking = false)
1297330f729Sjoerg         : Path(Path), StrictChecking(StrictChecking) {}
1307330f729Sjoerg   };
1317330f729Sjoerg   SmallVector<Candidate, 4> Candidates;
1327330f729Sjoerg 
1337330f729Sjoerg   // In decreasing order so we prefer newer versions to older versions.
1347330f729Sjoerg   std::initializer_list<const char *> Versions = {"8.0", "7.5", "7.0"};
135*e038c9c4Sjoerg   auto &FS = D.getVFS();
1367330f729Sjoerg 
1377330f729Sjoerg   if (Args.hasArg(clang::driver::options::OPT_cuda_path_EQ)) {
1387330f729Sjoerg     Candidates.emplace_back(
1397330f729Sjoerg         Args.getLastArgValue(clang::driver::options::OPT_cuda_path_EQ).str());
1407330f729Sjoerg   } else if (HostTriple.isOSWindows()) {
1417330f729Sjoerg     for (const char *Ver : Versions)
1427330f729Sjoerg       Candidates.emplace_back(
1437330f729Sjoerg           D.SysRoot + "/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v" +
1447330f729Sjoerg           Ver);
1457330f729Sjoerg   } else {
1467330f729Sjoerg     if (!Args.hasArg(clang::driver::options::OPT_cuda_path_ignore_env)) {
1477330f729Sjoerg       // Try to find ptxas binary. If the executable is located in a directory
1487330f729Sjoerg       // called 'bin/', its parent directory might be a good guess for a valid
1497330f729Sjoerg       // CUDA installation.
1507330f729Sjoerg       // However, some distributions might installs 'ptxas' to /usr/bin. In that
1517330f729Sjoerg       // case the candidate would be '/usr' which passes the following checks
1527330f729Sjoerg       // because '/usr/include' exists as well. To avoid this case, we always
1537330f729Sjoerg       // check for the directory potentially containing files for libdevice,
1547330f729Sjoerg       // even if the user passes -nocudalib.
1557330f729Sjoerg       if (llvm::ErrorOr<std::string> ptxas =
1567330f729Sjoerg               llvm::sys::findProgramByName("ptxas")) {
1577330f729Sjoerg         SmallString<256> ptxasAbsolutePath;
1587330f729Sjoerg         llvm::sys::fs::real_path(*ptxas, ptxasAbsolutePath);
1597330f729Sjoerg 
1607330f729Sjoerg         StringRef ptxasDir = llvm::sys::path::parent_path(ptxasAbsolutePath);
1617330f729Sjoerg         if (llvm::sys::path::filename(ptxasDir) == "bin")
162*e038c9c4Sjoerg           Candidates.emplace_back(
163*e038c9c4Sjoerg               std::string(llvm::sys::path::parent_path(ptxasDir)),
1647330f729Sjoerg               /*StrictChecking=*/true);
1657330f729Sjoerg       }
1667330f729Sjoerg     }
1677330f729Sjoerg 
1687330f729Sjoerg     Candidates.emplace_back(D.SysRoot + "/usr/local/cuda");
1697330f729Sjoerg     for (const char *Ver : Versions)
1707330f729Sjoerg       Candidates.emplace_back(D.SysRoot + "/usr/local/cuda-" + Ver);
1717330f729Sjoerg 
172*e038c9c4Sjoerg     Distro Dist(FS, llvm::Triple(llvm::sys::getProcessTriple()));
173*e038c9c4Sjoerg     if (Dist.IsDebian() || Dist.IsUbuntu())
1747330f729Sjoerg       // Special case for Debian to have nvidia-cuda-toolkit work
1757330f729Sjoerg       // out of the box. More info on http://bugs.debian.org/882505
1767330f729Sjoerg       Candidates.emplace_back(D.SysRoot + "/usr/lib/cuda");
1777330f729Sjoerg   }
1787330f729Sjoerg 
1797330f729Sjoerg   bool NoCudaLib = Args.hasArg(options::OPT_nogpulib);
1807330f729Sjoerg 
1817330f729Sjoerg   for (const auto &Candidate : Candidates) {
1827330f729Sjoerg     InstallPath = Candidate.Path;
183*e038c9c4Sjoerg     if (InstallPath.empty() || !FS.exists(InstallPath))
1847330f729Sjoerg       continue;
1857330f729Sjoerg 
1867330f729Sjoerg     BinPath = InstallPath + "/bin";
1877330f729Sjoerg     IncludePath = InstallPath + "/include";
1887330f729Sjoerg     LibDevicePath = InstallPath + "/nvvm/libdevice";
1897330f729Sjoerg 
1907330f729Sjoerg     if (!(FS.exists(IncludePath) && FS.exists(BinPath)))
1917330f729Sjoerg       continue;
1927330f729Sjoerg     bool CheckLibDevice = (!NoCudaLib || Candidate.StrictChecking);
1937330f729Sjoerg     if (CheckLibDevice && !FS.exists(LibDevicePath))
1947330f729Sjoerg       continue;
1957330f729Sjoerg 
1967330f729Sjoerg     // On Linux, we have both lib and lib64 directories, and we need to choose
1977330f729Sjoerg     // based on our triple.  On MacOS, we have only a lib directory.
1987330f729Sjoerg     //
1997330f729Sjoerg     // It's sufficient for our purposes to be flexible: If both lib and lib64
2007330f729Sjoerg     // exist, we choose whichever one matches our triple.  Otherwise, if only
2017330f729Sjoerg     // lib exists, we use it.
2027330f729Sjoerg     if (HostTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64"))
2037330f729Sjoerg       LibPath = InstallPath + "/lib64";
2047330f729Sjoerg     else if (FS.exists(InstallPath + "/lib"))
2057330f729Sjoerg       LibPath = InstallPath + "/lib";
2067330f729Sjoerg     else
2077330f729Sjoerg       continue;
2087330f729Sjoerg 
209*e038c9c4Sjoerg     CudaVersionInfo VersionInfo = {"", CudaVersion::UNKNOWN};
210*e038c9c4Sjoerg     if (auto VersionFile = FS.getBufferForFile(InstallPath + "/version.txt"))
211*e038c9c4Sjoerg       VersionInfo = parseCudaVersionFile((*VersionFile)->getBuffer());
212*e038c9c4Sjoerg     // If version file didn't give us the version, try to find it in cuda.h
213*e038c9c4Sjoerg     if (VersionInfo.Version == CudaVersion::UNKNOWN)
214*e038c9c4Sjoerg       if (auto CudaHFile = FS.getBufferForFile(InstallPath + "/include/cuda.h"))
215*e038c9c4Sjoerg         VersionInfo = parseCudaHFile((*CudaHFile)->getBuffer());
216*e038c9c4Sjoerg     // As the last resort, make an educated guess between CUDA-7.0, (which had
217*e038c9c4Sjoerg     // no version.txt file and had old-style libdevice bitcode ) and an unknown
218*e038c9c4Sjoerg     // recent CUDA version (no version.txt, new style bitcode).
219*e038c9c4Sjoerg     if (VersionInfo.Version == CudaVersion::UNKNOWN) {
220*e038c9c4Sjoerg       VersionInfo.Version = (FS.exists(LibDevicePath + "/libdevice.10.bc"))
221*e038c9c4Sjoerg                                 ? Version = CudaVersion::LATEST
222*e038c9c4Sjoerg                                 : Version = CudaVersion::CUDA_70;
223*e038c9c4Sjoerg       VersionInfo.DetectedVersion =
224*e038c9c4Sjoerg           "No version found in version.txt or cuda.h.";
2257330f729Sjoerg     }
2267330f729Sjoerg 
227*e038c9c4Sjoerg     Version = VersionInfo.Version;
228*e038c9c4Sjoerg     DetectedVersion = VersionInfo.DetectedVersion;
229*e038c9c4Sjoerg 
230*e038c9c4Sjoerg     // TODO(tra): remove the warning once we have all features of 10.2
231*e038c9c4Sjoerg     // and 11.0 implemented.
232*e038c9c4Sjoerg     DetectedVersionIsNotSupported = Version > CudaVersion::LATEST_SUPPORTED;
233*e038c9c4Sjoerg 
2347330f729Sjoerg     if (Version >= CudaVersion::CUDA_90) {
2357330f729Sjoerg       // CUDA-9+ uses single libdevice file for all GPU variants.
2367330f729Sjoerg       std::string FilePath = LibDevicePath + "/libdevice.10.bc";
2377330f729Sjoerg       if (FS.exists(FilePath)) {
238*e038c9c4Sjoerg         for (int Arch = (int)CudaArch::SM_30, E = (int)CudaArch::LAST; Arch < E;
239*e038c9c4Sjoerg              ++Arch) {
240*e038c9c4Sjoerg           CudaArch GpuArch = static_cast<CudaArch>(Arch);
241*e038c9c4Sjoerg           if (!IsNVIDIAGpuArch(GpuArch))
242*e038c9c4Sjoerg             continue;
243*e038c9c4Sjoerg           std::string GpuArchName(CudaArchToString(GpuArch));
2447330f729Sjoerg           LibDeviceMap[GpuArchName] = FilePath;
2457330f729Sjoerg         }
2467330f729Sjoerg       }
2477330f729Sjoerg     } else {
2487330f729Sjoerg       std::error_code EC;
249*e038c9c4Sjoerg       for (llvm::vfs::directory_iterator LI = FS.dir_begin(LibDevicePath, EC),
250*e038c9c4Sjoerg                                          LE;
2517330f729Sjoerg            !EC && LI != LE; LI = LI.increment(EC)) {
2527330f729Sjoerg         StringRef FilePath = LI->path();
2537330f729Sjoerg         StringRef FileName = llvm::sys::path::filename(FilePath);
2547330f729Sjoerg         // Process all bitcode filenames that look like
2557330f729Sjoerg         // libdevice.compute_XX.YY.bc
2567330f729Sjoerg         const StringRef LibDeviceName = "libdevice.";
2577330f729Sjoerg         if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
2587330f729Sjoerg           continue;
2597330f729Sjoerg         StringRef GpuArch = FileName.slice(
2607330f729Sjoerg             LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
2617330f729Sjoerg         LibDeviceMap[GpuArch] = FilePath.str();
2627330f729Sjoerg         // Insert map entries for specific devices with this compute
2637330f729Sjoerg         // capability. NVCC's choice of the libdevice library version is
2647330f729Sjoerg         // rather peculiar and depends on the CUDA version.
2657330f729Sjoerg         if (GpuArch == "compute_20") {
266*e038c9c4Sjoerg           LibDeviceMap["sm_20"] = std::string(FilePath);
267*e038c9c4Sjoerg           LibDeviceMap["sm_21"] = std::string(FilePath);
268*e038c9c4Sjoerg           LibDeviceMap["sm_32"] = std::string(FilePath);
2697330f729Sjoerg         } else if (GpuArch == "compute_30") {
270*e038c9c4Sjoerg           LibDeviceMap["sm_30"] = std::string(FilePath);
2717330f729Sjoerg           if (Version < CudaVersion::CUDA_80) {
272*e038c9c4Sjoerg             LibDeviceMap["sm_50"] = std::string(FilePath);
273*e038c9c4Sjoerg             LibDeviceMap["sm_52"] = std::string(FilePath);
274*e038c9c4Sjoerg             LibDeviceMap["sm_53"] = std::string(FilePath);
2757330f729Sjoerg           }
276*e038c9c4Sjoerg           LibDeviceMap["sm_60"] = std::string(FilePath);
277*e038c9c4Sjoerg           LibDeviceMap["sm_61"] = std::string(FilePath);
278*e038c9c4Sjoerg           LibDeviceMap["sm_62"] = std::string(FilePath);
2797330f729Sjoerg         } else if (GpuArch == "compute_35") {
280*e038c9c4Sjoerg           LibDeviceMap["sm_35"] = std::string(FilePath);
281*e038c9c4Sjoerg           LibDeviceMap["sm_37"] = std::string(FilePath);
2827330f729Sjoerg         } else if (GpuArch == "compute_50") {
2837330f729Sjoerg           if (Version >= CudaVersion::CUDA_80) {
284*e038c9c4Sjoerg             LibDeviceMap["sm_50"] = std::string(FilePath);
285*e038c9c4Sjoerg             LibDeviceMap["sm_52"] = std::string(FilePath);
286*e038c9c4Sjoerg             LibDeviceMap["sm_53"] = std::string(FilePath);
2877330f729Sjoerg           }
2887330f729Sjoerg         }
2897330f729Sjoerg       }
2907330f729Sjoerg     }
2917330f729Sjoerg 
2927330f729Sjoerg     // Check that we have found at least one libdevice that we can link in if
2937330f729Sjoerg     // -nocudalib hasn't been specified.
2947330f729Sjoerg     if (LibDeviceMap.empty() && !NoCudaLib)
2957330f729Sjoerg       continue;
2967330f729Sjoerg 
2977330f729Sjoerg     IsValid = true;
2987330f729Sjoerg     break;
2997330f729Sjoerg   }
3007330f729Sjoerg }
3017330f729Sjoerg 
AddCudaIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const3027330f729Sjoerg void CudaInstallationDetector::AddCudaIncludeArgs(
3037330f729Sjoerg     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
3047330f729Sjoerg   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3057330f729Sjoerg     // Add cuda_wrappers/* to our system include path.  This lets us wrap
3067330f729Sjoerg     // standard library headers.
3077330f729Sjoerg     SmallString<128> P(D.ResourceDir);
3087330f729Sjoerg     llvm::sys::path::append(P, "include");
3097330f729Sjoerg     llvm::sys::path::append(P, "cuda_wrappers");
3107330f729Sjoerg     CC1Args.push_back("-internal-isystem");
3117330f729Sjoerg     CC1Args.push_back(DriverArgs.MakeArgString(P));
3127330f729Sjoerg   }
3137330f729Sjoerg 
314*e038c9c4Sjoerg   if (DriverArgs.hasArg(options::OPT_nogpuinc))
3157330f729Sjoerg     return;
3167330f729Sjoerg 
3177330f729Sjoerg   if (!isValid()) {
3187330f729Sjoerg     D.Diag(diag::err_drv_no_cuda_installation);
3197330f729Sjoerg     return;
3207330f729Sjoerg   }
3217330f729Sjoerg 
3227330f729Sjoerg   CC1Args.push_back("-internal-isystem");
3237330f729Sjoerg   CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
3247330f729Sjoerg   CC1Args.push_back("-include");
3257330f729Sjoerg   CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
3267330f729Sjoerg }
3277330f729Sjoerg 
CheckCudaVersionSupportsArch(CudaArch Arch) const3287330f729Sjoerg void CudaInstallationDetector::CheckCudaVersionSupportsArch(
3297330f729Sjoerg     CudaArch Arch) const {
3307330f729Sjoerg   if (Arch == CudaArch::UNKNOWN || Version == CudaVersion::UNKNOWN ||
331*e038c9c4Sjoerg       ArchsWithBadVersion[(int)Arch])
3327330f729Sjoerg     return;
3337330f729Sjoerg 
3347330f729Sjoerg   auto MinVersion = MinVersionForCudaArch(Arch);
3357330f729Sjoerg   auto MaxVersion = MaxVersionForCudaArch(Arch);
3367330f729Sjoerg   if (Version < MinVersion || Version > MaxVersion) {
337*e038c9c4Sjoerg     ArchsWithBadVersion[(int)Arch] = true;
3387330f729Sjoerg     D.Diag(diag::err_drv_cuda_version_unsupported)
3397330f729Sjoerg         << CudaArchToString(Arch) << CudaVersionToString(MinVersion)
3407330f729Sjoerg         << CudaVersionToString(MaxVersion) << InstallPath
3417330f729Sjoerg         << CudaVersionToString(Version);
3427330f729Sjoerg   }
3437330f729Sjoerg }
3447330f729Sjoerg 
print(raw_ostream & OS) const3457330f729Sjoerg void CudaInstallationDetector::print(raw_ostream &OS) const {
3467330f729Sjoerg   if (isValid())
3477330f729Sjoerg     OS << "Found CUDA installation: " << InstallPath << ", version "
3487330f729Sjoerg        << CudaVersionToString(Version) << "\n";
3497330f729Sjoerg }
3507330f729Sjoerg 
3517330f729Sjoerg namespace {
3527330f729Sjoerg /// Debug info level for the NVPTX devices. We may need to emit different debug
3537330f729Sjoerg /// info level for the host and for the device itselfi. This type controls
3547330f729Sjoerg /// emission of the debug info for the devices. It either prohibits disable info
3557330f729Sjoerg /// emission completely, or emits debug directives only, or emits same debug
3567330f729Sjoerg /// info as for the host.
3577330f729Sjoerg enum DeviceDebugInfoLevel {
3587330f729Sjoerg   DisableDebugInfo,        /// Do not emit debug info for the devices.
3597330f729Sjoerg   DebugDirectivesOnly,     /// Emit only debug directives.
3607330f729Sjoerg   EmitSameDebugInfoAsHost, /// Use the same debug info level just like for the
3617330f729Sjoerg                            /// host.
3627330f729Sjoerg };
3637330f729Sjoerg } // anonymous namespace
3647330f729Sjoerg 
3657330f729Sjoerg /// Define debug info level for the NVPTX devices. If the debug info for both
3667330f729Sjoerg /// the host and device are disabled (-g0/-ggdb0 or no debug options at all). If
3677330f729Sjoerg /// only debug directives are requested for the both host and device
3687330f729Sjoerg /// (-gline-directvies-only), or the debug info only for the device is disabled
3697330f729Sjoerg /// (optimization is on and --cuda-noopt-device-debug was not specified), the
3707330f729Sjoerg /// debug directves only must be emitted for the device. Otherwise, use the same
3717330f729Sjoerg /// debug info level just like for the host (with the limitations of only
3727330f729Sjoerg /// supported DWARF2 standard).
mustEmitDebugInfo(const ArgList & Args)3737330f729Sjoerg static DeviceDebugInfoLevel mustEmitDebugInfo(const ArgList &Args) {
3747330f729Sjoerg   const Arg *A = Args.getLastArg(options::OPT_O_Group);
3757330f729Sjoerg   bool IsDebugEnabled = !A || A->getOption().matches(options::OPT_O0) ||
3767330f729Sjoerg                         Args.hasFlag(options::OPT_cuda_noopt_device_debug,
3777330f729Sjoerg                                      options::OPT_no_cuda_noopt_device_debug,
3787330f729Sjoerg                                      /*Default=*/false);
3797330f729Sjoerg   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3807330f729Sjoerg     const Option &Opt = A->getOption();
3817330f729Sjoerg     if (Opt.matches(options::OPT_gN_Group)) {
3827330f729Sjoerg       if (Opt.matches(options::OPT_g0) || Opt.matches(options::OPT_ggdb0))
3837330f729Sjoerg         return DisableDebugInfo;
3847330f729Sjoerg       if (Opt.matches(options::OPT_gline_directives_only))
3857330f729Sjoerg         return DebugDirectivesOnly;
3867330f729Sjoerg     }
3877330f729Sjoerg     return IsDebugEnabled ? EmitSameDebugInfoAsHost : DebugDirectivesOnly;
3887330f729Sjoerg   }
389*e038c9c4Sjoerg   return willEmitRemarks(Args) ? DebugDirectivesOnly : DisableDebugInfo;
3907330f729Sjoerg }
3917330f729Sjoerg 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3927330f729Sjoerg void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
3937330f729Sjoerg                                     const InputInfo &Output,
3947330f729Sjoerg                                     const InputInfoList &Inputs,
3957330f729Sjoerg                                     const ArgList &Args,
3967330f729Sjoerg                                     const char *LinkingOutput) const {
3977330f729Sjoerg   const auto &TC =
3987330f729Sjoerg       static_cast<const toolchains::CudaToolChain &>(getToolChain());
3997330f729Sjoerg   assert(TC.getTriple().isNVPTX() && "Wrong platform");
4007330f729Sjoerg 
4017330f729Sjoerg   StringRef GPUArchName;
4027330f729Sjoerg   // If this is an OpenMP action we need to extract the device architecture
4037330f729Sjoerg   // from the -march=arch option. This option may come from -Xopenmp-target
4047330f729Sjoerg   // flag or the default value.
4057330f729Sjoerg   if (JA.isDeviceOffloading(Action::OFK_OpenMP)) {
4067330f729Sjoerg     GPUArchName = Args.getLastArgValue(options::OPT_march_EQ);
4077330f729Sjoerg     assert(!GPUArchName.empty() && "Must have an architecture passed in.");
4087330f729Sjoerg   } else
4097330f729Sjoerg     GPUArchName = JA.getOffloadingArch();
4107330f729Sjoerg 
4117330f729Sjoerg   // Obtain architecture from the action.
4127330f729Sjoerg   CudaArch gpu_arch = StringToCudaArch(GPUArchName);
4137330f729Sjoerg   assert(gpu_arch != CudaArch::UNKNOWN &&
4147330f729Sjoerg          "Device action expected to have an architecture.");
4157330f729Sjoerg 
4167330f729Sjoerg   // Check that our installation's ptxas supports gpu_arch.
4177330f729Sjoerg   if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
4187330f729Sjoerg     TC.CudaInstallation.CheckCudaVersionSupportsArch(gpu_arch);
4197330f729Sjoerg   }
4207330f729Sjoerg 
4217330f729Sjoerg   ArgStringList CmdArgs;
4227330f729Sjoerg   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
4237330f729Sjoerg   DeviceDebugInfoLevel DIKind = mustEmitDebugInfo(Args);
4247330f729Sjoerg   if (DIKind == EmitSameDebugInfoAsHost) {
4257330f729Sjoerg     // ptxas does not accept -g option if optimization is enabled, so
4267330f729Sjoerg     // we ignore the compiler's -O* options if we want debug info.
4277330f729Sjoerg     CmdArgs.push_back("-g");
4287330f729Sjoerg     CmdArgs.push_back("--dont-merge-basicblocks");
4297330f729Sjoerg     CmdArgs.push_back("--return-at-end");
4307330f729Sjoerg   } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4317330f729Sjoerg     // Map the -O we received to -O{0,1,2,3}.
4327330f729Sjoerg     //
4337330f729Sjoerg     // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
4347330f729Sjoerg     // default, so it may correspond more closely to the spirit of clang -O2.
4357330f729Sjoerg 
4367330f729Sjoerg     // -O3 seems like the least-bad option when -Osomething is specified to
4377330f729Sjoerg     // clang but it isn't handled below.
4387330f729Sjoerg     StringRef OOpt = "3";
4397330f729Sjoerg     if (A->getOption().matches(options::OPT_O4) ||
4407330f729Sjoerg         A->getOption().matches(options::OPT_Ofast))
4417330f729Sjoerg       OOpt = "3";
4427330f729Sjoerg     else if (A->getOption().matches(options::OPT_O0))
4437330f729Sjoerg       OOpt = "0";
4447330f729Sjoerg     else if (A->getOption().matches(options::OPT_O)) {
4457330f729Sjoerg       // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
4467330f729Sjoerg       OOpt = llvm::StringSwitch<const char *>(A->getValue())
4477330f729Sjoerg                  .Case("1", "1")
4487330f729Sjoerg                  .Case("2", "2")
4497330f729Sjoerg                  .Case("3", "3")
4507330f729Sjoerg                  .Case("s", "2")
4517330f729Sjoerg                  .Case("z", "2")
4527330f729Sjoerg                  .Default("2");
4537330f729Sjoerg     }
4547330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
4557330f729Sjoerg   } else {
4567330f729Sjoerg     // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
4577330f729Sjoerg     // to no optimizations, but ptxas's default is -O3.
4587330f729Sjoerg     CmdArgs.push_back("-O0");
4597330f729Sjoerg   }
4607330f729Sjoerg   if (DIKind == DebugDirectivesOnly)
4617330f729Sjoerg     CmdArgs.push_back("-lineinfo");
4627330f729Sjoerg 
4637330f729Sjoerg   // Pass -v to ptxas if it was passed to the driver.
4647330f729Sjoerg   if (Args.hasArg(options::OPT_v))
4657330f729Sjoerg     CmdArgs.push_back("-v");
4667330f729Sjoerg 
4677330f729Sjoerg   CmdArgs.push_back("--gpu-name");
4687330f729Sjoerg   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
4697330f729Sjoerg   CmdArgs.push_back("--output-file");
4707330f729Sjoerg   CmdArgs.push_back(Args.MakeArgString(TC.getInputFilename(Output)));
4717330f729Sjoerg   for (const auto& II : Inputs)
4727330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
4737330f729Sjoerg 
4747330f729Sjoerg   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
4757330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString(A));
4767330f729Sjoerg 
4777330f729Sjoerg   bool Relocatable = false;
4787330f729Sjoerg   if (JA.isOffloading(Action::OFK_OpenMP))
4797330f729Sjoerg     // In OpenMP we need to generate relocatable code.
4807330f729Sjoerg     Relocatable = Args.hasFlag(options::OPT_fopenmp_relocatable_target,
4817330f729Sjoerg                                options::OPT_fnoopenmp_relocatable_target,
4827330f729Sjoerg                                /*Default=*/true);
4837330f729Sjoerg   else if (JA.isOffloading(Action::OFK_Cuda))
4847330f729Sjoerg     Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
4857330f729Sjoerg                                options::OPT_fno_gpu_rdc, /*Default=*/false);
4867330f729Sjoerg 
4877330f729Sjoerg   if (Relocatable)
4887330f729Sjoerg     CmdArgs.push_back("-c");
4897330f729Sjoerg 
4907330f729Sjoerg   const char *Exec;
4917330f729Sjoerg   if (Arg *A = Args.getLastArg(options::OPT_ptxas_path_EQ))
4927330f729Sjoerg     Exec = A->getValue();
4937330f729Sjoerg   else
4947330f729Sjoerg     Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
495*e038c9c4Sjoerg   C.addCommand(std::make_unique<Command>(
496*e038c9c4Sjoerg       JA, *this,
497*e038c9c4Sjoerg       ResponseFileSupport{ResponseFileSupport::RF_Full, llvm::sys::WEM_UTF8,
498*e038c9c4Sjoerg                           "--options-file"},
499*e038c9c4Sjoerg       Exec, CmdArgs, Inputs, Output));
5007330f729Sjoerg }
5017330f729Sjoerg 
shouldIncludePTX(const ArgList & Args,const char * gpu_arch)5027330f729Sjoerg static bool shouldIncludePTX(const ArgList &Args, const char *gpu_arch) {
5037330f729Sjoerg   bool includePTX = true;
5047330f729Sjoerg   for (Arg *A : Args) {
5057330f729Sjoerg     if (!(A->getOption().matches(options::OPT_cuda_include_ptx_EQ) ||
5067330f729Sjoerg           A->getOption().matches(options::OPT_no_cuda_include_ptx_EQ)))
5077330f729Sjoerg       continue;
5087330f729Sjoerg     A->claim();
5097330f729Sjoerg     const StringRef ArchStr = A->getValue();
5107330f729Sjoerg     if (ArchStr == "all" || ArchStr == gpu_arch) {
5117330f729Sjoerg       includePTX = A->getOption().matches(options::OPT_cuda_include_ptx_EQ);
5127330f729Sjoerg       continue;
5137330f729Sjoerg     }
5147330f729Sjoerg   }
5157330f729Sjoerg   return includePTX;
5167330f729Sjoerg }
5177330f729Sjoerg 
5187330f729Sjoerg // All inputs to this linker must be from CudaDeviceActions, as we need to look
5197330f729Sjoerg // at the Inputs' Actions in order to figure out which GPU architecture they
5207330f729Sjoerg // correspond to.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const5217330f729Sjoerg void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
5227330f729Sjoerg                                  const InputInfo &Output,
5237330f729Sjoerg                                  const InputInfoList &Inputs,
5247330f729Sjoerg                                  const ArgList &Args,
5257330f729Sjoerg                                  const char *LinkingOutput) const {
5267330f729Sjoerg   const auto &TC =
5277330f729Sjoerg       static_cast<const toolchains::CudaToolChain &>(getToolChain());
5287330f729Sjoerg   assert(TC.getTriple().isNVPTX() && "Wrong platform");
5297330f729Sjoerg 
5307330f729Sjoerg   ArgStringList CmdArgs;
5317330f729Sjoerg   if (TC.CudaInstallation.version() <= CudaVersion::CUDA_100)
5327330f729Sjoerg     CmdArgs.push_back("--cuda");
5337330f729Sjoerg   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
5347330f729Sjoerg   CmdArgs.push_back(Args.MakeArgString("--create"));
5357330f729Sjoerg   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
5367330f729Sjoerg   if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
5377330f729Sjoerg     CmdArgs.push_back("-g");
5387330f729Sjoerg 
5397330f729Sjoerg   for (const auto& II : Inputs) {
5407330f729Sjoerg     auto *A = II.getAction();
5417330f729Sjoerg     assert(A->getInputs().size() == 1 &&
5427330f729Sjoerg            "Device offload action is expected to have a single input");
5437330f729Sjoerg     const char *gpu_arch_str = A->getOffloadingArch();
5447330f729Sjoerg     assert(gpu_arch_str &&
5457330f729Sjoerg            "Device action expected to have associated a GPU architecture!");
5467330f729Sjoerg     CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
5477330f729Sjoerg 
5487330f729Sjoerg     if (II.getType() == types::TY_PP_Asm &&
5497330f729Sjoerg         !shouldIncludePTX(Args, gpu_arch_str))
5507330f729Sjoerg       continue;
5517330f729Sjoerg     // We need to pass an Arch of the form "sm_XX" for cubin files and
5527330f729Sjoerg     // "compute_XX" for ptx.
553*e038c9c4Sjoerg     const char *Arch = (II.getType() == types::TY_PP_Asm)
554*e038c9c4Sjoerg                            ? CudaArchToVirtualArchString(gpu_arch)
5557330f729Sjoerg                            : gpu_arch_str;
5567330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
5577330f729Sjoerg                                          Arch + ",file=" + II.getFilename()));
5587330f729Sjoerg   }
5597330f729Sjoerg 
5607330f729Sjoerg   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
5617330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString(A));
5627330f729Sjoerg 
5637330f729Sjoerg   const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
564*e038c9c4Sjoerg   C.addCommand(std::make_unique<Command>(
565*e038c9c4Sjoerg       JA, *this,
566*e038c9c4Sjoerg       ResponseFileSupport{ResponseFileSupport::RF_Full, llvm::sys::WEM_UTF8,
567*e038c9c4Sjoerg                           "--options-file"},
568*e038c9c4Sjoerg       Exec, CmdArgs, Inputs, Output));
5697330f729Sjoerg }
5707330f729Sjoerg 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const5717330f729Sjoerg void NVPTX::OpenMPLinker::ConstructJob(Compilation &C, const JobAction &JA,
5727330f729Sjoerg                                        const InputInfo &Output,
5737330f729Sjoerg                                        const InputInfoList &Inputs,
5747330f729Sjoerg                                        const ArgList &Args,
5757330f729Sjoerg                                        const char *LinkingOutput) const {
5767330f729Sjoerg   const auto &TC =
5777330f729Sjoerg       static_cast<const toolchains::CudaToolChain &>(getToolChain());
5787330f729Sjoerg   assert(TC.getTriple().isNVPTX() && "Wrong platform");
5797330f729Sjoerg 
5807330f729Sjoerg   ArgStringList CmdArgs;
5817330f729Sjoerg 
5827330f729Sjoerg   // OpenMP uses nvlink to link cubin files. The result will be embedded in the
5837330f729Sjoerg   // host binary by the host linker.
5847330f729Sjoerg   assert(!JA.isHostOffloading(Action::OFK_OpenMP) &&
5857330f729Sjoerg          "CUDA toolchain not expected for an OpenMP host device.");
5867330f729Sjoerg 
5877330f729Sjoerg   if (Output.isFilename()) {
5887330f729Sjoerg     CmdArgs.push_back("-o");
5897330f729Sjoerg     CmdArgs.push_back(Output.getFilename());
5907330f729Sjoerg   } else
5917330f729Sjoerg     assert(Output.isNothing() && "Invalid output.");
5927330f729Sjoerg   if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
5937330f729Sjoerg     CmdArgs.push_back("-g");
5947330f729Sjoerg 
5957330f729Sjoerg   if (Args.hasArg(options::OPT_v))
5967330f729Sjoerg     CmdArgs.push_back("-v");
5977330f729Sjoerg 
5987330f729Sjoerg   StringRef GPUArch =
5997330f729Sjoerg       Args.getLastArgValue(options::OPT_march_EQ);
6007330f729Sjoerg   assert(!GPUArch.empty() && "At least one GPU Arch required for ptxas.");
6017330f729Sjoerg 
6027330f729Sjoerg   CmdArgs.push_back("-arch");
6037330f729Sjoerg   CmdArgs.push_back(Args.MakeArgString(GPUArch));
6047330f729Sjoerg 
6057330f729Sjoerg   // Add paths specified in LIBRARY_PATH environment variable as -L options.
6067330f729Sjoerg   addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
6077330f729Sjoerg 
6087330f729Sjoerg   // Add paths for the default clang library path.
6097330f729Sjoerg   SmallString<256> DefaultLibPath =
6107330f729Sjoerg       llvm::sys::path::parent_path(TC.getDriver().Dir);
6117330f729Sjoerg   llvm::sys::path::append(DefaultLibPath, "lib" CLANG_LIBDIR_SUFFIX);
6127330f729Sjoerg   CmdArgs.push_back(Args.MakeArgString(Twine("-L") + DefaultLibPath));
6137330f729Sjoerg 
6147330f729Sjoerg   for (const auto &II : Inputs) {
6157330f729Sjoerg     if (II.getType() == types::TY_LLVM_IR ||
6167330f729Sjoerg         II.getType() == types::TY_LTO_IR ||
6177330f729Sjoerg         II.getType() == types::TY_LTO_BC ||
6187330f729Sjoerg         II.getType() == types::TY_LLVM_BC) {
6197330f729Sjoerg       C.getDriver().Diag(diag::err_drv_no_linker_llvm_support)
6207330f729Sjoerg           << getToolChain().getTripleString();
6217330f729Sjoerg       continue;
6227330f729Sjoerg     }
6237330f729Sjoerg 
6247330f729Sjoerg     // Currently, we only pass the input files to the linker, we do not pass
6257330f729Sjoerg     // any libraries that may be valid only for the host.
6267330f729Sjoerg     if (!II.isFilename())
6277330f729Sjoerg       continue;
6287330f729Sjoerg 
6297330f729Sjoerg     const char *CubinF = C.addTempFile(
6307330f729Sjoerg         C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
6317330f729Sjoerg 
6327330f729Sjoerg     CmdArgs.push_back(CubinF);
6337330f729Sjoerg   }
6347330f729Sjoerg 
6357330f729Sjoerg   const char *Exec =
6367330f729Sjoerg       Args.MakeArgString(getToolChain().GetProgramPath("nvlink"));
637*e038c9c4Sjoerg   C.addCommand(std::make_unique<Command>(
638*e038c9c4Sjoerg       JA, *this,
639*e038c9c4Sjoerg       ResponseFileSupport{ResponseFileSupport::RF_Full, llvm::sys::WEM_UTF8,
640*e038c9c4Sjoerg                           "--options-file"},
641*e038c9c4Sjoerg       Exec, CmdArgs, Inputs, Output));
6427330f729Sjoerg }
6437330f729Sjoerg 
6447330f729Sjoerg /// CUDA toolchain.  Our assembler is ptxas, and our "linker" is fatbinary,
6457330f729Sjoerg /// which isn't properly a linker but nonetheless performs the step of stitching
6467330f729Sjoerg /// together object files from the assembler into a single blob.
6477330f729Sjoerg 
CudaToolChain(const Driver & D,const llvm::Triple & Triple,const ToolChain & HostTC,const ArgList & Args,const Action::OffloadKind OK)6487330f729Sjoerg CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
6497330f729Sjoerg                              const ToolChain &HostTC, const ArgList &Args,
6507330f729Sjoerg                              const Action::OffloadKind OK)
6517330f729Sjoerg     : ToolChain(D, Triple, Args), HostTC(HostTC),
6527330f729Sjoerg       CudaInstallation(D, HostTC.getTriple(), Args), OK(OK) {
653*e038c9c4Sjoerg   if (CudaInstallation.isValid()) {
654*e038c9c4Sjoerg     CudaInstallation.WarnIfUnsupportedVersion();
655*e038c9c4Sjoerg     getProgramPaths().push_back(std::string(CudaInstallation.getBinPath()));
656*e038c9c4Sjoerg   }
6577330f729Sjoerg   // Lookup binaries into the driver directory, this is used to
6587330f729Sjoerg   // discover the clang-offload-bundler executable.
6597330f729Sjoerg   getProgramPaths().push_back(getDriver().Dir);
6607330f729Sjoerg }
6617330f729Sjoerg 
getInputFilename(const InputInfo & Input) const6627330f729Sjoerg std::string CudaToolChain::getInputFilename(const InputInfo &Input) const {
6637330f729Sjoerg   // Only object files are changed, for example assembly files keep their .s
6647330f729Sjoerg   // extensions. CUDA also continues to use .o as they don't use nvlink but
6657330f729Sjoerg   // fatbinary.
6667330f729Sjoerg   if (!(OK == Action::OFK_OpenMP && Input.getType() == types::TY_Object))
6677330f729Sjoerg     return ToolChain::getInputFilename(Input);
6687330f729Sjoerg 
6697330f729Sjoerg   // Replace extension for object files with cubin because nvlink relies on
6707330f729Sjoerg   // these particular file names.
6717330f729Sjoerg   SmallString<256> Filename(ToolChain::getInputFilename(Input));
6727330f729Sjoerg   llvm::sys::path::replace_extension(Filename, "cubin");
673*e038c9c4Sjoerg   return std::string(Filename.str());
6747330f729Sjoerg }
6757330f729Sjoerg 
addClangTargetOptions(const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args,Action::OffloadKind DeviceOffloadingKind) const6767330f729Sjoerg void CudaToolChain::addClangTargetOptions(
6777330f729Sjoerg     const llvm::opt::ArgList &DriverArgs,
6787330f729Sjoerg     llvm::opt::ArgStringList &CC1Args,
6797330f729Sjoerg     Action::OffloadKind DeviceOffloadingKind) const {
6807330f729Sjoerg   HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
6817330f729Sjoerg 
6827330f729Sjoerg   StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
6837330f729Sjoerg   assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
6847330f729Sjoerg   assert((DeviceOffloadingKind == Action::OFK_OpenMP ||
6857330f729Sjoerg           DeviceOffloadingKind == Action::OFK_Cuda) &&
6867330f729Sjoerg          "Only OpenMP or CUDA offloading kinds are supported for NVIDIA GPUs.");
6877330f729Sjoerg 
6887330f729Sjoerg   if (DeviceOffloadingKind == Action::OFK_Cuda) {
6897330f729Sjoerg     CC1Args.push_back("-fcuda-is-device");
6907330f729Sjoerg 
6917330f729Sjoerg     if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
6927330f729Sjoerg                            options::OPT_fno_cuda_approx_transcendentals, false))
6937330f729Sjoerg       CC1Args.push_back("-fcuda-approx-transcendentals");
6947330f729Sjoerg   }
6957330f729Sjoerg 
6967330f729Sjoerg   if (DriverArgs.hasArg(options::OPT_nogpulib))
6977330f729Sjoerg     return;
6987330f729Sjoerg 
6997330f729Sjoerg   if (DeviceOffloadingKind == Action::OFK_OpenMP &&
7007330f729Sjoerg       DriverArgs.hasArg(options::OPT_S))
7017330f729Sjoerg     return;
7027330f729Sjoerg 
703*e038c9c4Sjoerg   std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(GpuArch);
704*e038c9c4Sjoerg   if (LibDeviceFile.empty()) {
7057330f729Sjoerg     getDriver().Diag(diag::err_drv_no_cuda_libdevice) << GpuArch;
7067330f729Sjoerg     return;
7077330f729Sjoerg   }
7087330f729Sjoerg 
7097330f729Sjoerg   CC1Args.push_back("-mlink-builtin-bitcode");
7107330f729Sjoerg   CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
7117330f729Sjoerg 
712*e038c9c4Sjoerg   clang::CudaVersion CudaInstallationVersion = CudaInstallation.version();
713*e038c9c4Sjoerg 
7147330f729Sjoerg   // New CUDA versions often introduce new instructions that are only supported
7157330f729Sjoerg   // by new PTX version, so we need to raise PTX level to enable them in NVPTX
7167330f729Sjoerg   // back-end.
7177330f729Sjoerg   const char *PtxFeature = nullptr;
718*e038c9c4Sjoerg   switch (CudaInstallationVersion) {
719*e038c9c4Sjoerg #define CASE_CUDA_VERSION(CUDA_VER, PTX_VER)                                   \
720*e038c9c4Sjoerg   case CudaVersion::CUDA_##CUDA_VER:                                           \
721*e038c9c4Sjoerg     PtxFeature = "+ptx" #PTX_VER;                                              \
7227330f729Sjoerg     break;
723*e038c9c4Sjoerg     CASE_CUDA_VERSION(112, 72);
724*e038c9c4Sjoerg     CASE_CUDA_VERSION(111, 71);
725*e038c9c4Sjoerg     CASE_CUDA_VERSION(110, 70);
726*e038c9c4Sjoerg     CASE_CUDA_VERSION(102, 65);
727*e038c9c4Sjoerg     CASE_CUDA_VERSION(101, 64);
728*e038c9c4Sjoerg     CASE_CUDA_VERSION(100, 63);
729*e038c9c4Sjoerg     CASE_CUDA_VERSION(92, 61);
730*e038c9c4Sjoerg     CASE_CUDA_VERSION(91, 61);
731*e038c9c4Sjoerg     CASE_CUDA_VERSION(90, 60);
732*e038c9c4Sjoerg #undef CASE_CUDA_VERSION
7337330f729Sjoerg   default:
7347330f729Sjoerg     PtxFeature = "+ptx42";
7357330f729Sjoerg   }
7367330f729Sjoerg   CC1Args.append({"-target-feature", PtxFeature});
7377330f729Sjoerg   if (DriverArgs.hasFlag(options::OPT_fcuda_short_ptr,
7387330f729Sjoerg                          options::OPT_fno_cuda_short_ptr, false))
7397330f729Sjoerg     CC1Args.append({"-mllvm", "--nvptx-short-ptr"});
7407330f729Sjoerg 
741*e038c9c4Sjoerg   if (CudaInstallationVersion >= CudaVersion::UNKNOWN)
742*e038c9c4Sjoerg     CC1Args.push_back(
743*e038c9c4Sjoerg         DriverArgs.MakeArgString(Twine("-target-sdk-version=") +
744*e038c9c4Sjoerg                                  CudaVersionToString(CudaInstallationVersion)));
7457330f729Sjoerg 
7467330f729Sjoerg   if (DeviceOffloadingKind == Action::OFK_OpenMP) {
747*e038c9c4Sjoerg     if (CudaInstallationVersion < CudaVersion::CUDA_92) {
748*e038c9c4Sjoerg       getDriver().Diag(
749*e038c9c4Sjoerg           diag::err_drv_omp_offload_target_cuda_version_not_support)
750*e038c9c4Sjoerg           << CudaVersionToString(CudaInstallationVersion);
751*e038c9c4Sjoerg       return;
7527330f729Sjoerg     }
7537330f729Sjoerg 
754*e038c9c4Sjoerg     std::string BitcodeSuffix = "nvptx-" + GpuArch.str();
755*e038c9c4Sjoerg     addOpenMPDeviceRTL(getDriver(), DriverArgs, CC1Args, BitcodeSuffix,
756*e038c9c4Sjoerg                        getTriple());
757*e038c9c4Sjoerg   }
758*e038c9c4Sjoerg }
7597330f729Sjoerg 
getDefaultDenormalModeForType(const llvm::opt::ArgList & DriverArgs,const JobAction & JA,const llvm::fltSemantics * FPType) const760*e038c9c4Sjoerg llvm::DenormalMode CudaToolChain::getDefaultDenormalModeForType(
761*e038c9c4Sjoerg     const llvm::opt::ArgList &DriverArgs, const JobAction &JA,
762*e038c9c4Sjoerg     const llvm::fltSemantics *FPType) const {
763*e038c9c4Sjoerg   if (JA.getOffloadingDeviceKind() == Action::OFK_Cuda) {
764*e038c9c4Sjoerg     if (FPType && FPType == &llvm::APFloat::IEEEsingle() &&
765*e038c9c4Sjoerg         DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,
766*e038c9c4Sjoerg                            options::OPT_fno_gpu_flush_denormals_to_zero, false))
767*e038c9c4Sjoerg       return llvm::DenormalMode::getPreserveSign();
7687330f729Sjoerg   }
769*e038c9c4Sjoerg 
770*e038c9c4Sjoerg   assert(JA.getOffloadingDeviceKind() != Action::OFK_Host);
771*e038c9c4Sjoerg   return llvm::DenormalMode::getIEEE();
7727330f729Sjoerg }
7737330f729Sjoerg 
supportsDebugInfoOption(const llvm::opt::Arg * A) const7747330f729Sjoerg bool CudaToolChain::supportsDebugInfoOption(const llvm::opt::Arg *A) const {
7757330f729Sjoerg   const Option &O = A->getOption();
7767330f729Sjoerg   return (O.matches(options::OPT_gN_Group) &&
7777330f729Sjoerg           !O.matches(options::OPT_gmodules)) ||
7787330f729Sjoerg          O.matches(options::OPT_g_Flag) ||
7797330f729Sjoerg          O.matches(options::OPT_ggdbN_Group) || O.matches(options::OPT_ggdb) ||
7807330f729Sjoerg          O.matches(options::OPT_gdwarf) || O.matches(options::OPT_gdwarf_2) ||
7817330f729Sjoerg          O.matches(options::OPT_gdwarf_3) || O.matches(options::OPT_gdwarf_4) ||
7827330f729Sjoerg          O.matches(options::OPT_gdwarf_5) ||
7837330f729Sjoerg          O.matches(options::OPT_gcolumn_info);
7847330f729Sjoerg }
7857330f729Sjoerg 
adjustDebugInfoKind(codegenoptions::DebugInfoKind & DebugInfoKind,const ArgList & Args) const7867330f729Sjoerg void CudaToolChain::adjustDebugInfoKind(
7877330f729Sjoerg     codegenoptions::DebugInfoKind &DebugInfoKind, const ArgList &Args) const {
7887330f729Sjoerg   switch (mustEmitDebugInfo(Args)) {
7897330f729Sjoerg   case DisableDebugInfo:
7907330f729Sjoerg     DebugInfoKind = codegenoptions::NoDebugInfo;
7917330f729Sjoerg     break;
7927330f729Sjoerg   case DebugDirectivesOnly:
7937330f729Sjoerg     DebugInfoKind = codegenoptions::DebugDirectivesOnly;
7947330f729Sjoerg     break;
7957330f729Sjoerg   case EmitSameDebugInfoAsHost:
7967330f729Sjoerg     // Use same debug info level as the host.
7977330f729Sjoerg     break;
7987330f729Sjoerg   }
7997330f729Sjoerg }
8007330f729Sjoerg 
AddCudaIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const8017330f729Sjoerg void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
8027330f729Sjoerg                                        ArgStringList &CC1Args) const {
8037330f729Sjoerg   // Check our CUDA version if we're going to include the CUDA headers.
804*e038c9c4Sjoerg   if (!DriverArgs.hasArg(options::OPT_nogpuinc) &&
8057330f729Sjoerg       !DriverArgs.hasArg(options::OPT_no_cuda_version_check)) {
8067330f729Sjoerg     StringRef Arch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
8077330f729Sjoerg     assert(!Arch.empty() && "Must have an explicit GPU arch.");
8087330f729Sjoerg     CudaInstallation.CheckCudaVersionSupportsArch(StringToCudaArch(Arch));
8097330f729Sjoerg   }
8107330f729Sjoerg   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
8117330f729Sjoerg }
8127330f729Sjoerg 
8137330f729Sjoerg llvm::opt::DerivedArgList *
TranslateArgs(const llvm::opt::DerivedArgList & Args,StringRef BoundArch,Action::OffloadKind DeviceOffloadKind) const8147330f729Sjoerg CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
8157330f729Sjoerg                              StringRef BoundArch,
8167330f729Sjoerg                              Action::OffloadKind DeviceOffloadKind) const {
8177330f729Sjoerg   DerivedArgList *DAL =
8187330f729Sjoerg       HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
8197330f729Sjoerg   if (!DAL)
8207330f729Sjoerg     DAL = new DerivedArgList(Args.getBaseArgs());
8217330f729Sjoerg 
8227330f729Sjoerg   const OptTable &Opts = getDriver().getOpts();
8237330f729Sjoerg 
8247330f729Sjoerg   // For OpenMP device offloading, append derived arguments. Make sure
8257330f729Sjoerg   // flags are not duplicated.
8267330f729Sjoerg   // Also append the compute capability.
8277330f729Sjoerg   if (DeviceOffloadKind == Action::OFK_OpenMP) {
8287330f729Sjoerg     for (Arg *A : Args) {
8297330f729Sjoerg       bool IsDuplicate = false;
8307330f729Sjoerg       for (Arg *DALArg : *DAL) {
8317330f729Sjoerg         if (A == DALArg) {
8327330f729Sjoerg           IsDuplicate = true;
8337330f729Sjoerg           break;
8347330f729Sjoerg         }
8357330f729Sjoerg       }
8367330f729Sjoerg       if (!IsDuplicate)
8377330f729Sjoerg         DAL->append(A);
8387330f729Sjoerg     }
8397330f729Sjoerg 
8407330f729Sjoerg     StringRef Arch = DAL->getLastArgValue(options::OPT_march_EQ);
8417330f729Sjoerg     if (Arch.empty())
8427330f729Sjoerg       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ),
8437330f729Sjoerg                         CLANG_OPENMP_NVPTX_DEFAULT_ARCH);
8447330f729Sjoerg 
8457330f729Sjoerg     return DAL;
8467330f729Sjoerg   }
8477330f729Sjoerg 
8487330f729Sjoerg   for (Arg *A : Args) {
8497330f729Sjoerg     DAL->append(A);
8507330f729Sjoerg   }
8517330f729Sjoerg 
8527330f729Sjoerg   if (!BoundArch.empty()) {
8537330f729Sjoerg     DAL->eraseArg(options::OPT_march_EQ);
8547330f729Sjoerg     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
8557330f729Sjoerg   }
8567330f729Sjoerg   return DAL;
8577330f729Sjoerg }
8587330f729Sjoerg 
buildAssembler() const8597330f729Sjoerg Tool *CudaToolChain::buildAssembler() const {
8607330f729Sjoerg   return new tools::NVPTX::Assembler(*this);
8617330f729Sjoerg }
8627330f729Sjoerg 
buildLinker() const8637330f729Sjoerg Tool *CudaToolChain::buildLinker() const {
8647330f729Sjoerg   if (OK == Action::OFK_OpenMP)
8657330f729Sjoerg     return new tools::NVPTX::OpenMPLinker(*this);
8667330f729Sjoerg   return new tools::NVPTX::Linker(*this);
8677330f729Sjoerg }
8687330f729Sjoerg 
addClangWarningOptions(ArgStringList & CC1Args) const8697330f729Sjoerg void CudaToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
8707330f729Sjoerg   HostTC.addClangWarningOptions(CC1Args);
8717330f729Sjoerg }
8727330f729Sjoerg 
8737330f729Sjoerg ToolChain::CXXStdlibType
GetCXXStdlibType(const ArgList & Args) const8747330f729Sjoerg CudaToolChain::GetCXXStdlibType(const ArgList &Args) const {
8757330f729Sjoerg   return HostTC.GetCXXStdlibType(Args);
8767330f729Sjoerg }
8777330f729Sjoerg 
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const8787330f729Sjoerg void CudaToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
8797330f729Sjoerg                                               ArgStringList &CC1Args) const {
8807330f729Sjoerg   HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
8817330f729Sjoerg }
8827330f729Sjoerg 
AddClangCXXStdlibIncludeArgs(const ArgList & Args,ArgStringList & CC1Args) const8837330f729Sjoerg void CudaToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
8847330f729Sjoerg                                                  ArgStringList &CC1Args) const {
8857330f729Sjoerg   HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
8867330f729Sjoerg }
8877330f729Sjoerg 
AddIAMCUIncludeArgs(const ArgList & Args,ArgStringList & CC1Args) const8887330f729Sjoerg void CudaToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
8897330f729Sjoerg                                         ArgStringList &CC1Args) const {
8907330f729Sjoerg   HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
8917330f729Sjoerg }
8927330f729Sjoerg 
getSupportedSanitizers() const8937330f729Sjoerg SanitizerMask CudaToolChain::getSupportedSanitizers() const {
8947330f729Sjoerg   // The CudaToolChain only supports sanitizers in the sense that it allows
8957330f729Sjoerg   // sanitizer arguments on the command line if they are supported by the host
8967330f729Sjoerg   // toolchain. The CudaToolChain will actually ignore any command line
8977330f729Sjoerg   // arguments for any of these "supported" sanitizers. That means that no
8987330f729Sjoerg   // sanitization of device code is actually supported at this time.
8997330f729Sjoerg   //
9007330f729Sjoerg   // This behavior is necessary because the host and device toolchains
9017330f729Sjoerg   // invocations often share the command line, so the device toolchain must
9027330f729Sjoerg   // tolerate flags meant only for the host toolchain.
9037330f729Sjoerg   return HostTC.getSupportedSanitizers();
9047330f729Sjoerg }
9057330f729Sjoerg 
computeMSVCVersion(const Driver * D,const ArgList & Args) const9067330f729Sjoerg VersionTuple CudaToolChain::computeMSVCVersion(const Driver *D,
9077330f729Sjoerg                                                const ArgList &Args) const {
9087330f729Sjoerg   return HostTC.computeMSVCVersion(D, Args);
9097330f729Sjoerg }
910