1 //===--- Cuda.cpp - Cuda Tool and ToolChain Implementations -----*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 #include "CommonArgs.h"
11 #include "InputInfo.h"
12 #include "clang/Basic/Cuda.h"
13 #include "clang/Config/config.h"
14 #include "clang/Driver/Compilation.h"
15 #include "clang/Driver/Distro.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "llvm/Option/ArgList.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/Process.h"
23 #include "llvm/Support/Program.h"
24 #include "llvm/Support/VirtualFileSystem.h"
25 #include <system_error>
27 using namespace clang::driver;
28 using namespace clang::driver::toolchains;
29 using namespace clang::driver::tools;
30 using namespace clang;
31 using namespace llvm::opt;
33 // Parses the contents of version.txt in an CUDA installation. It should
34 // contain one line of the from e.g. "CUDA Version 7.5.2".
35 static CudaVersion ParseCudaVersionFile(llvm::StringRef V) {
36 if (!V.startswith("CUDA Version "))
37 return CudaVersion::UNKNOWN;
38 V = V.substr(strlen("CUDA Version "));
39 int Major = -1, Minor = -1;
40 auto First = V.split('.');
41 auto Second = First.second.split('.');
42 if (First.first.getAsInteger(10, Major) ||
43 Second.first.getAsInteger(10, Minor))
44 return CudaVersion::UNKNOWN;
46 if (Major == 7 && Minor == 0) {
47 // This doesn't appear to ever happen -- version.txt doesn't exist in the
48 // CUDA 7 installs I've seen. But no harm in checking.
49 return CudaVersion::CUDA_70;
51 if (Major == 7 && Minor == 5)
52 return CudaVersion::CUDA_75;
53 if (Major == 8 && Minor == 0)
54 return CudaVersion::CUDA_80;
55 if (Major == 9 && Minor == 0)
56 return CudaVersion::CUDA_90;
57 if (Major == 9 && Minor == 1)
58 return CudaVersion::CUDA_91;
59 if (Major == 9 && Minor == 2)
60 return CudaVersion::CUDA_92;
61 if (Major == 10 && Minor == 0)
62 return CudaVersion::CUDA_100;
63 if (Major == 10 && Minor == 1)
64 return CudaVersion::CUDA_101;
65 return CudaVersion::UNKNOWN;
68 CudaInstallationDetector::CudaInstallationDetector(
69 const Driver &D, const llvm::Triple &HostTriple,
70 const llvm::opt::ArgList &Args)
76 Candidate(std::string Path, bool StrictChecking = false)
77 : Path(Path), StrictChecking(StrictChecking) {}
79 SmallVector<Candidate, 4> Candidates;
81 // In decreasing order so we prefer newer versions to older versions.
82 std::initializer_list<const char *> Versions = {"8.0", "7.5", "7.0"};
84 if (Args.hasArg(clang::driver::options::OPT_cuda_path_EQ)) {
85 Candidates.emplace_back(
86 Args.getLastArgValue(clang::driver::options::OPT_cuda_path_EQ).str());
87 } else if (HostTriple.isOSWindows()) {
88 for (const char *Ver : Versions)
89 Candidates.emplace_back(
90 D.SysRoot + "/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v" +
93 if (!Args.hasArg(clang::driver::options::OPT_cuda_path_ignore_env)) {
94 // Try to find ptxas binary. If the executable is located in a directory
95 // called 'bin/', its parent directory might be a good guess for a valid
97 // However, some distributions might installs 'ptxas' to /usr/bin. In that
98 // case the candidate would be '/usr' which passes the following checks
99 // because '/usr/include' exists as well. To avoid this case, we always
100 // check for the directory potentially containing files for libdevice,
101 // even if the user passes -nocudalib.
102 if (llvm::ErrorOr<std::string> ptxas =
103 llvm::sys::findProgramByName("ptxas")) {
104 SmallString<256> ptxasAbsolutePath;
105 llvm::sys::fs::real_path(*ptxas, ptxasAbsolutePath);
107 StringRef ptxasDir = llvm::sys::path::parent_path(ptxasAbsolutePath);
108 if (llvm::sys::path::filename(ptxasDir) == "bin")
109 Candidates.emplace_back(llvm::sys::path::parent_path(ptxasDir),
110 /*StrictChecking=*/true);
114 Candidates.emplace_back(D.SysRoot + "/usr/local/cuda");
115 for (const char *Ver : Versions)
116 Candidates.emplace_back(D.SysRoot + "/usr/local/cuda-" + Ver);
118 Distro Dist(D.getVFS(), llvm::Triple(llvm::sys::getProcessTriple()));
119 if (Dist.IsDebian() || Dist.IsUbuntu())
120 // Special case for Debian to have nvidia-cuda-toolkit work
121 // out of the box. More info on http://bugs.debian.org/882505
122 Candidates.emplace_back(D.SysRoot + "/usr/lib/cuda");
125 bool NoCudaLib = Args.hasArg(options::OPT_nogpulib);
127 for (const auto &Candidate : Candidates) {
128 InstallPath = Candidate.Path;
129 if (InstallPath.empty() || !D.getVFS().exists(InstallPath))
132 BinPath = InstallPath + "/bin";
133 IncludePath = InstallPath + "/include";
134 LibDevicePath = InstallPath + "/nvvm/libdevice";
136 auto &FS = D.getVFS();
137 if (!(FS.exists(IncludePath) && FS.exists(BinPath)))
139 bool CheckLibDevice = (!NoCudaLib || Candidate.StrictChecking);
140 if (CheckLibDevice && !FS.exists(LibDevicePath))
143 // On Linux, we have both lib and lib64 directories, and we need to choose
144 // based on our triple. On MacOS, we have only a lib directory.
146 // It's sufficient for our purposes to be flexible: If both lib and lib64
147 // exist, we choose whichever one matches our triple. Otherwise, if only
148 // lib exists, we use it.
149 if (HostTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64"))
150 LibPath = InstallPath + "/lib64";
151 else if (FS.exists(InstallPath + "/lib"))
152 LibPath = InstallPath + "/lib";
156 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
157 FS.getBufferForFile(InstallPath + "/version.txt");
159 // CUDA 7.0 doesn't have a version.txt, so guess that's our version if
160 // version.txt isn't present.
161 Version = CudaVersion::CUDA_70;
163 Version = ParseCudaVersionFile((*VersionFile)->getBuffer());
166 if (Version >= CudaVersion::CUDA_90) {
167 // CUDA-9+ uses single libdevice file for all GPU variants.
168 std::string FilePath = LibDevicePath + "/libdevice.10.bc";
169 if (FS.exists(FilePath)) {
170 for (const char *GpuArchName :
171 {"sm_30", "sm_32", "sm_35", "sm_37", "sm_50", "sm_52", "sm_53",
172 "sm_60", "sm_61", "sm_62", "sm_70", "sm_72", "sm_75"}) {
173 const CudaArch GpuArch = StringToCudaArch(GpuArchName);
174 if (Version >= MinVersionForCudaArch(GpuArch) &&
175 Version <= MaxVersionForCudaArch(GpuArch))
176 LibDeviceMap[GpuArchName] = FilePath;
181 for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE;
182 !EC && LI != LE; LI = LI.increment(EC)) {
183 StringRef FilePath = LI->path();
184 StringRef FileName = llvm::sys::path::filename(FilePath);
185 // Process all bitcode filenames that look like
186 // libdevice.compute_XX.YY.bc
187 const StringRef LibDeviceName = "libdevice.";
188 if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
190 StringRef GpuArch = FileName.slice(
191 LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
192 LibDeviceMap[GpuArch] = FilePath.str();
193 // Insert map entries for specific devices with this compute
194 // capability. NVCC's choice of the libdevice library version is
195 // rather peculiar and depends on the CUDA version.
196 if (GpuArch == "compute_20") {
197 LibDeviceMap["sm_20"] = FilePath;
198 LibDeviceMap["sm_21"] = FilePath;
199 LibDeviceMap["sm_32"] = FilePath;
200 } else if (GpuArch == "compute_30") {
201 LibDeviceMap["sm_30"] = FilePath;
202 if (Version < CudaVersion::CUDA_80) {
203 LibDeviceMap["sm_50"] = FilePath;
204 LibDeviceMap["sm_52"] = FilePath;
205 LibDeviceMap["sm_53"] = FilePath;
207 LibDeviceMap["sm_60"] = FilePath;
208 LibDeviceMap["sm_61"] = FilePath;
209 LibDeviceMap["sm_62"] = FilePath;
210 } else if (GpuArch == "compute_35") {
211 LibDeviceMap["sm_35"] = FilePath;
212 LibDeviceMap["sm_37"] = FilePath;
213 } else if (GpuArch == "compute_50") {
214 if (Version >= CudaVersion::CUDA_80) {
215 LibDeviceMap["sm_50"] = FilePath;
216 LibDeviceMap["sm_52"] = FilePath;
217 LibDeviceMap["sm_53"] = FilePath;
223 // Check that we have found at least one libdevice that we can link in if
224 // -nocudalib hasn't been specified.
225 if (LibDeviceMap.empty() && !NoCudaLib)
233 void CudaInstallationDetector::AddCudaIncludeArgs(
234 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
235 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
236 // Add cuda_wrappers/* to our system include path. This lets us wrap
237 // standard library headers.
238 SmallString<128> P(D.ResourceDir);
239 llvm::sys::path::append(P, "include");
240 llvm::sys::path::append(P, "cuda_wrappers");
241 CC1Args.push_back("-internal-isystem");
242 CC1Args.push_back(DriverArgs.MakeArgString(P));
245 if (DriverArgs.hasArg(options::OPT_nocudainc))
249 D.Diag(diag::err_drv_no_cuda_installation);
253 CC1Args.push_back("-internal-isystem");
254 CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
255 CC1Args.push_back("-include");
256 CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
259 void CudaInstallationDetector::CheckCudaVersionSupportsArch(
260 CudaArch Arch) const {
261 if (Arch == CudaArch::UNKNOWN || Version == CudaVersion::UNKNOWN ||
262 ArchsWithBadVersion.count(Arch) > 0)
265 auto MinVersion = MinVersionForCudaArch(Arch);
266 auto MaxVersion = MaxVersionForCudaArch(Arch);
267 if (Version < MinVersion || Version > MaxVersion) {
268 ArchsWithBadVersion.insert(Arch);
269 D.Diag(diag::err_drv_cuda_version_unsupported)
270 << CudaArchToString(Arch) << CudaVersionToString(MinVersion)
271 << CudaVersionToString(MaxVersion) << InstallPath
272 << CudaVersionToString(Version);
276 void CudaInstallationDetector::print(raw_ostream &OS) const {
278 OS << "Found CUDA installation: " << InstallPath << ", version "
279 << CudaVersionToString(Version) << "\n";
283 /// Debug info level for the NVPTX devices. We may need to emit different debug
284 /// info level for the host and for the device itselfi. This type controls
285 /// emission of the debug info for the devices. It either prohibits disable info
286 /// emission completely, or emits debug directives only, or emits same debug
287 /// info as for the host.
288 enum DeviceDebugInfoLevel {
289 DisableDebugInfo, /// Do not emit debug info for the devices.
290 DebugDirectivesOnly, /// Emit only debug directives.
291 EmitSameDebugInfoAsHost, /// Use the same debug info level just like for the
294 } // anonymous namespace
296 /// Define debug info level for the NVPTX devices. If the debug info for both
297 /// the host and device are disabled (-g0/-ggdb0 or no debug options at all). If
298 /// only debug directives are requested for the both host and device
299 /// (-gline-directvies-only), or the debug info only for the device is disabled
300 /// (optimization is on and --cuda-noopt-device-debug was not specified), the
301 /// debug directves only must be emitted for the device. Otherwise, use the same
302 /// debug info level just like for the host (with the limitations of only
303 /// supported DWARF2 standard).
304 static DeviceDebugInfoLevel mustEmitDebugInfo(const ArgList &Args) {
305 const Arg *A = Args.getLastArg(options::OPT_O_Group);
306 bool IsDebugEnabled = !A || A->getOption().matches(options::OPT_O0) ||
307 Args.hasFlag(options::OPT_cuda_noopt_device_debug,
308 options::OPT_no_cuda_noopt_device_debug,
310 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
311 const Option &Opt = A->getOption();
312 if (Opt.matches(options::OPT_gN_Group)) {
313 if (Opt.matches(options::OPT_g0) || Opt.matches(options::OPT_ggdb0))
314 return DisableDebugInfo;
315 if (Opt.matches(options::OPT_gline_directives_only))
316 return DebugDirectivesOnly;
318 return IsDebugEnabled ? EmitSameDebugInfoAsHost : DebugDirectivesOnly;
320 return DisableDebugInfo;
323 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
324 const InputInfo &Output,
325 const InputInfoList &Inputs,
327 const char *LinkingOutput) const {
329 static_cast<const toolchains::CudaToolChain &>(getToolChain());
330 assert(TC.getTriple().isNVPTX() && "Wrong platform");
332 StringRef GPUArchName;
333 // If this is an OpenMP action we need to extract the device architecture
334 // from the -march=arch option. This option may come from -Xopenmp-target
335 // flag or the default value.
336 if (JA.isDeviceOffloading(Action::OFK_OpenMP)) {
337 GPUArchName = Args.getLastArgValue(options::OPT_march_EQ);
338 assert(!GPUArchName.empty() && "Must have an architecture passed in.");
340 GPUArchName = JA.getOffloadingArch();
342 // Obtain architecture from the action.
343 CudaArch gpu_arch = StringToCudaArch(GPUArchName);
344 assert(gpu_arch != CudaArch::UNKNOWN &&
345 "Device action expected to have an architecture.");
347 // Check that our installation's ptxas supports gpu_arch.
348 if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
349 TC.CudaInstallation.CheckCudaVersionSupportsArch(gpu_arch);
352 ArgStringList CmdArgs;
353 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
354 DeviceDebugInfoLevel DIKind = mustEmitDebugInfo(Args);
355 if (DIKind == EmitSameDebugInfoAsHost) {
356 // ptxas does not accept -g option if optimization is enabled, so
357 // we ignore the compiler's -O* options if we want debug info.
358 CmdArgs.push_back("-g");
359 CmdArgs.push_back("--dont-merge-basicblocks");
360 CmdArgs.push_back("--return-at-end");
361 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
362 // Map the -O we received to -O{0,1,2,3}.
364 // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
365 // default, so it may correspond more closely to the spirit of clang -O2.
367 // -O3 seems like the least-bad option when -Osomething is specified to
368 // clang but it isn't handled below.
369 StringRef OOpt = "3";
370 if (A->getOption().matches(options::OPT_O4) ||
371 A->getOption().matches(options::OPT_Ofast))
373 else if (A->getOption().matches(options::OPT_O0))
375 else if (A->getOption().matches(options::OPT_O)) {
376 // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
377 OOpt = llvm::StringSwitch<const char *>(A->getValue())
385 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
387 // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
388 // to no optimizations, but ptxas's default is -O3.
389 CmdArgs.push_back("-O0");
391 if (DIKind == DebugDirectivesOnly)
392 CmdArgs.push_back("-lineinfo");
394 // Pass -v to ptxas if it was passed to the driver.
395 if (Args.hasArg(options::OPT_v))
396 CmdArgs.push_back("-v");
398 CmdArgs.push_back("--gpu-name");
399 CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
400 CmdArgs.push_back("--output-file");
401 CmdArgs.push_back(Args.MakeArgString(TC.getInputFilename(Output)));
402 for (const auto& II : Inputs)
403 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
405 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
406 CmdArgs.push_back(Args.MakeArgString(A));
408 bool Relocatable = false;
409 if (JA.isOffloading(Action::OFK_OpenMP))
410 // In OpenMP we need to generate relocatable code.
411 Relocatable = Args.hasFlag(options::OPT_fopenmp_relocatable_target,
412 options::OPT_fnoopenmp_relocatable_target,
414 else if (JA.isOffloading(Action::OFK_Cuda))
415 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
416 options::OPT_fno_gpu_rdc, /*Default=*/false);
419 CmdArgs.push_back("-c");
422 if (Arg *A = Args.getLastArg(options::OPT_ptxas_path_EQ))
423 Exec = A->getValue();
425 Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
426 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
429 static bool shouldIncludePTX(const ArgList &Args, const char *gpu_arch) {
430 bool includePTX = true;
431 for (Arg *A : Args) {
432 if (!(A->getOption().matches(options::OPT_cuda_include_ptx_EQ) ||
433 A->getOption().matches(options::OPT_no_cuda_include_ptx_EQ)))
436 const StringRef ArchStr = A->getValue();
437 if (ArchStr == "all" || ArchStr == gpu_arch) {
438 includePTX = A->getOption().matches(options::OPT_cuda_include_ptx_EQ);
445 // All inputs to this linker must be from CudaDeviceActions, as we need to look
446 // at the Inputs' Actions in order to figure out which GPU architecture they
448 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
449 const InputInfo &Output,
450 const InputInfoList &Inputs,
452 const char *LinkingOutput) const {
454 static_cast<const toolchains::CudaToolChain &>(getToolChain());
455 assert(TC.getTriple().isNVPTX() && "Wrong platform");
457 ArgStringList CmdArgs;
458 if (TC.CudaInstallation.version() <= CudaVersion::CUDA_100)
459 CmdArgs.push_back("--cuda");
460 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
461 CmdArgs.push_back(Args.MakeArgString("--create"));
462 CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
463 if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
464 CmdArgs.push_back("-g");
466 for (const auto& II : Inputs) {
467 auto *A = II.getAction();
468 assert(A->getInputs().size() == 1 &&
469 "Device offload action is expected to have a single input");
470 const char *gpu_arch_str = A->getOffloadingArch();
471 assert(gpu_arch_str &&
472 "Device action expected to have associated a GPU architecture!");
473 CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
475 if (II.getType() == types::TY_PP_Asm &&
476 !shouldIncludePTX(Args, gpu_arch_str))
478 // We need to pass an Arch of the form "sm_XX" for cubin files and
479 // "compute_XX" for ptx.
481 (II.getType() == types::TY_PP_Asm)
482 ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
484 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
485 Arch + ",file=" + II.getFilename()));
488 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
489 CmdArgs.push_back(Args.MakeArgString(A));
491 const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
492 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
495 void NVPTX::OpenMPLinker::ConstructJob(Compilation &C, const JobAction &JA,
496 const InputInfo &Output,
497 const InputInfoList &Inputs,
499 const char *LinkingOutput) const {
501 static_cast<const toolchains::CudaToolChain &>(getToolChain());
502 assert(TC.getTriple().isNVPTX() && "Wrong platform");
504 ArgStringList CmdArgs;
506 // OpenMP uses nvlink to link cubin files. The result will be embedded in the
507 // host binary by the host linker.
508 assert(!JA.isHostOffloading(Action::OFK_OpenMP) &&
509 "CUDA toolchain not expected for an OpenMP host device.");
511 if (Output.isFilename()) {
512 CmdArgs.push_back("-o");
513 CmdArgs.push_back(Output.getFilename());
515 assert(Output.isNothing() && "Invalid output.");
516 if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
517 CmdArgs.push_back("-g");
519 if (Args.hasArg(options::OPT_v))
520 CmdArgs.push_back("-v");
523 Args.getLastArgValue(options::OPT_march_EQ);
524 assert(!GPUArch.empty() && "At least one GPU Arch required for ptxas.");
526 CmdArgs.push_back("-arch");
527 CmdArgs.push_back(Args.MakeArgString(GPUArch));
529 // Assume that the directory specified with --libomptarget_nvptx_path
530 // contains the static library libomptarget-nvptx.a.
531 if (const Arg *A = Args.getLastArg(options::OPT_libomptarget_nvptx_path_EQ))
532 CmdArgs.push_back(Args.MakeArgString(Twine("-L") + A->getValue()));
534 // Add paths specified in LIBRARY_PATH environment variable as -L options.
535 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
537 // Add paths for the default clang library path.
538 SmallString<256> DefaultLibPath =
539 llvm::sys::path::parent_path(TC.getDriver().Dir);
540 llvm::sys::path::append(DefaultLibPath, "lib" CLANG_LIBDIR_SUFFIX);
541 CmdArgs.push_back(Args.MakeArgString(Twine("-L") + DefaultLibPath));
543 // Add linking against library implementing OpenMP calls on NVPTX target.
544 CmdArgs.push_back("-lomptarget-nvptx");
546 for (const auto &II : Inputs) {
547 if (II.getType() == types::TY_LLVM_IR ||
548 II.getType() == types::TY_LTO_IR ||
549 II.getType() == types::TY_LTO_BC ||
550 II.getType() == types::TY_LLVM_BC) {
551 C.getDriver().Diag(diag::err_drv_no_linker_llvm_support)
552 << getToolChain().getTripleString();
556 // Currently, we only pass the input files to the linker, we do not pass
557 // any libraries that may be valid only for the host.
558 if (!II.isFilename())
561 const char *CubinF = C.addTempFile(
562 C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
564 CmdArgs.push_back(CubinF);
568 Args.MakeArgString(getToolChain().GetProgramPath("nvlink"));
569 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
572 /// CUDA toolchain. Our assembler is ptxas, and our "linker" is fatbinary,
573 /// which isn't properly a linker but nonetheless performs the step of stitching
574 /// together object files from the assembler into a single blob.
576 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
577 const ToolChain &HostTC, const ArgList &Args,
578 const Action::OffloadKind OK)
579 : ToolChain(D, Triple, Args), HostTC(HostTC),
580 CudaInstallation(D, HostTC.getTriple(), Args), OK(OK) {
581 if (CudaInstallation.isValid())
582 getProgramPaths().push_back(CudaInstallation.getBinPath());
583 // Lookup binaries into the driver directory, this is used to
584 // discover the clang-offload-bundler executable.
585 getProgramPaths().push_back(getDriver().Dir);
588 std::string CudaToolChain::getInputFilename(const InputInfo &Input) const {
589 // Only object files are changed, for example assembly files keep their .s
590 // extensions. CUDA also continues to use .o as they don't use nvlink but
592 if (!(OK == Action::OFK_OpenMP && Input.getType() == types::TY_Object))
593 return ToolChain::getInputFilename(Input);
595 // Replace extension for object files with cubin because nvlink relies on
596 // these particular file names.
597 SmallString<256> Filename(ToolChain::getInputFilename(Input));
598 llvm::sys::path::replace_extension(Filename, "cubin");
599 return Filename.str();
602 void CudaToolChain::addClangTargetOptions(
603 const llvm::opt::ArgList &DriverArgs,
604 llvm::opt::ArgStringList &CC1Args,
605 Action::OffloadKind DeviceOffloadingKind) const {
606 HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
608 StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
609 assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
610 assert((DeviceOffloadingKind == Action::OFK_OpenMP ||
611 DeviceOffloadingKind == Action::OFK_Cuda) &&
612 "Only OpenMP or CUDA offloading kinds are supported for NVIDIA GPUs.");
614 if (DeviceOffloadingKind == Action::OFK_Cuda) {
615 CC1Args.push_back("-fcuda-is-device");
617 if (DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
618 options::OPT_fno_cuda_flush_denormals_to_zero, false))
619 CC1Args.push_back("-fcuda-flush-denormals-to-zero");
621 if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
622 options::OPT_fno_cuda_approx_transcendentals, false))
623 CC1Args.push_back("-fcuda-approx-transcendentals");
625 if (DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
627 CC1Args.push_back("-fgpu-rdc");
630 if (DriverArgs.hasArg(options::OPT_nogpulib))
633 std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(GpuArch);
635 if (LibDeviceFile.empty()) {
636 if (DeviceOffloadingKind == Action::OFK_OpenMP &&
637 DriverArgs.hasArg(options::OPT_S))
640 getDriver().Diag(diag::err_drv_no_cuda_libdevice) << GpuArch;
644 CC1Args.push_back("-mlink-builtin-bitcode");
645 CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
647 // New CUDA versions often introduce new instructions that are only supported
648 // by new PTX version, so we need to raise PTX level to enable them in NVPTX
650 const char *PtxFeature = nullptr;
651 switch(CudaInstallation.version()) {
652 case CudaVersion::CUDA_101:
653 PtxFeature = "+ptx64";
655 case CudaVersion::CUDA_100:
656 PtxFeature = "+ptx63";
658 case CudaVersion::CUDA_92:
659 PtxFeature = "+ptx61";
661 case CudaVersion::CUDA_91:
662 PtxFeature = "+ptx61";
664 case CudaVersion::CUDA_90:
665 PtxFeature = "+ptx60";
668 PtxFeature = "+ptx42";
670 CC1Args.append({"-target-feature", PtxFeature});
671 if (DriverArgs.hasFlag(options::OPT_fcuda_short_ptr,
672 options::OPT_fno_cuda_short_ptr, false))
673 CC1Args.append({"-mllvm", "--nvptx-short-ptr"});
675 if (CudaInstallation.version() >= CudaVersion::UNKNOWN)
676 CC1Args.push_back(DriverArgs.MakeArgString(
677 Twine("-target-sdk-version=") +
678 CudaVersionToString(CudaInstallation.version())));
680 if (DeviceOffloadingKind == Action::OFK_OpenMP) {
681 SmallVector<StringRef, 8> LibraryPaths;
682 if (const Arg *A = DriverArgs.getLastArg(options::OPT_libomptarget_nvptx_path_EQ))
683 LibraryPaths.push_back(A->getValue());
685 // Add user defined library paths from LIBRARY_PATH.
686 llvm::Optional<std::string> LibPath =
687 llvm::sys::Process::GetEnv("LIBRARY_PATH");
689 SmallVector<StringRef, 8> Frags;
690 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
691 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
692 for (StringRef Path : Frags)
693 LibraryPaths.emplace_back(Path.trim());
696 // Add path to lib / lib64 folder.
697 SmallString<256> DefaultLibPath =
698 llvm::sys::path::parent_path(getDriver().Dir);
699 llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
700 LibraryPaths.emplace_back(DefaultLibPath.c_str());
702 std::string LibOmpTargetName =
703 "libomptarget-nvptx-" + GpuArch.str() + ".bc";
704 bool FoundBCLibrary = false;
705 for (StringRef LibraryPath : LibraryPaths) {
706 SmallString<128> LibOmpTargetFile(LibraryPath);
707 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
708 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
709 CC1Args.push_back("-mlink-builtin-bitcode");
710 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
711 FoundBCLibrary = true;
716 getDriver().Diag(diag::warn_drv_omp_offload_target_missingbcruntime)
721 bool CudaToolChain::supportsDebugInfoOption(const llvm::opt::Arg *A) const {
722 const Option &O = A->getOption();
723 return (O.matches(options::OPT_gN_Group) &&
724 !O.matches(options::OPT_gmodules)) ||
725 O.matches(options::OPT_g_Flag) ||
726 O.matches(options::OPT_ggdbN_Group) || O.matches(options::OPT_ggdb) ||
727 O.matches(options::OPT_gdwarf) || O.matches(options::OPT_gdwarf_2) ||
728 O.matches(options::OPT_gdwarf_3) || O.matches(options::OPT_gdwarf_4) ||
729 O.matches(options::OPT_gdwarf_5) ||
730 O.matches(options::OPT_gcolumn_info);
733 void CudaToolChain::adjustDebugInfoKind(
734 codegenoptions::DebugInfoKind &DebugInfoKind, const ArgList &Args) const {
735 switch (mustEmitDebugInfo(Args)) {
736 case DisableDebugInfo:
737 DebugInfoKind = codegenoptions::NoDebugInfo;
739 case DebugDirectivesOnly:
740 DebugInfoKind = codegenoptions::DebugDirectivesOnly;
742 case EmitSameDebugInfoAsHost:
743 // Use same debug info level as the host.
748 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
749 ArgStringList &CC1Args) const {
750 // Check our CUDA version if we're going to include the CUDA headers.
751 if (!DriverArgs.hasArg(options::OPT_nocudainc) &&
752 !DriverArgs.hasArg(options::OPT_no_cuda_version_check)) {
753 StringRef Arch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
754 assert(!Arch.empty() && "Must have an explicit GPU arch.");
755 CudaInstallation.CheckCudaVersionSupportsArch(StringToCudaArch(Arch));
757 CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
760 llvm::opt::DerivedArgList *
761 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
763 Action::OffloadKind DeviceOffloadKind) const {
764 DerivedArgList *DAL =
765 HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
767 DAL = new DerivedArgList(Args.getBaseArgs());
769 const OptTable &Opts = getDriver().getOpts();
771 // For OpenMP device offloading, append derived arguments. Make sure
772 // flags are not duplicated.
773 // Also append the compute capability.
774 if (DeviceOffloadKind == Action::OFK_OpenMP) {
775 for (Arg *A : Args) {
776 bool IsDuplicate = false;
777 for (Arg *DALArg : *DAL) {
787 StringRef Arch = DAL->getLastArgValue(options::OPT_march_EQ);
789 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ),
790 CLANG_OPENMP_NVPTX_DEFAULT_ARCH);
795 for (Arg *A : Args) {
796 if (A->getOption().matches(options::OPT_Xarch__)) {
797 // Skip this argument unless the architecture matches BoundArch
798 if (BoundArch.empty() || A->getValue(0) != BoundArch)
801 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
802 unsigned Prev = Index;
803 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
805 // If the argument parsing failed or more than one argument was
806 // consumed, the -Xarch_ argument's parameter tried to consume
807 // extra arguments. Emit an error and ignore.
809 // We also want to disallow any options which would alter the
810 // driver behavior; that isn't going to work in our model. We
811 // use isDriverOption() as an approximation, although things
812 // like -O4 are going to slip through.
813 if (!XarchArg || Index > Prev + 1) {
814 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
815 << A->getAsString(Args);
817 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
818 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
819 << A->getAsString(Args);
822 XarchArg->setBaseArg(A);
823 A = XarchArg.release();
824 DAL->AddSynthesizedArg(A);
829 if (!BoundArch.empty()) {
830 DAL->eraseArg(options::OPT_march_EQ);
831 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
836 Tool *CudaToolChain::buildAssembler() const {
837 return new tools::NVPTX::Assembler(*this);
840 Tool *CudaToolChain::buildLinker() const {
841 if (OK == Action::OFK_OpenMP)
842 return new tools::NVPTX::OpenMPLinker(*this);
843 return new tools::NVPTX::Linker(*this);
846 void CudaToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
847 HostTC.addClangWarningOptions(CC1Args);
850 ToolChain::CXXStdlibType
851 CudaToolChain::GetCXXStdlibType(const ArgList &Args) const {
852 return HostTC.GetCXXStdlibType(Args);
855 void CudaToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
856 ArgStringList &CC1Args) const {
857 HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
860 void CudaToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
861 ArgStringList &CC1Args) const {
862 HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
865 void CudaToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
866 ArgStringList &CC1Args) const {
867 HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
870 SanitizerMask CudaToolChain::getSupportedSanitizers() const {
871 // The CudaToolChain only supports sanitizers in the sense that it allows
872 // sanitizer arguments on the command line if they are supported by the host
873 // toolchain. The CudaToolChain will actually ignore any command line
874 // arguments for any of these "supported" sanitizers. That means that no
875 // sanitization of device code is actually supported at this time.
877 // This behavior is necessary because the host and device toolchains
878 // invocations often share the command line, so the device toolchain must
879 // tolerate flags meant only for the host toolchain.
880 return HostTC.getSupportedSanitizers();
883 VersionTuple CudaToolChain::computeMSVCVersion(const Driver *D,
884 const ArgList &Args) const {
885 return HostTC.computeMSVCVersion(D, Args);