1 //===--- Cuda.cpp - Cuda Tool and ToolChain Implementations -----*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Cuda.h"
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/Host.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/Process.h"
24 #include "llvm/Support/Program.h"
25 #include "llvm/Support/TargetParser.h"
26 #include "llvm/Support/VirtualFileSystem.h"
27 #include <system_error>
28 
29 using namespace clang::driver;
30 using namespace clang::driver::toolchains;
31 using namespace clang::driver::tools;
32 using namespace clang;
33 using namespace llvm::opt;
34 
35 // Parses the contents of version.txt in an CUDA installation.  It should
36 // contain one line of the from e.g. "CUDA Version 7.5.2".
37 void CudaInstallationDetector::ParseCudaVersionFile(llvm::StringRef V) {
38   Version = CudaVersion::UNKNOWN;
39   if (!V.startswith("CUDA Version "))
40     return;
41   V = V.substr(strlen("CUDA Version "));
42   SmallVector<StringRef,4> VersionParts;
43   V.split(VersionParts, '.');
44   if (VersionParts.size() < 2)
45     return;
46   DetectedVersion = join_items(".", VersionParts[0], VersionParts[1]);
47   Version = CudaStringToVersion(DetectedVersion);
48   if (Version != CudaVersion::UNKNOWN)
49     return;
50 
51   Version = CudaVersion::LATEST;
52   DetectedVersionIsNotSupported = true;
53 }
54 
55 void CudaInstallationDetector::WarnIfUnsupportedVersion() {
56   if (DetectedVersionIsNotSupported)
57     D.Diag(diag::warn_drv_unknown_cuda_version)
58         << DetectedVersion << CudaVersionToString(Version);
59 }
60 
61 CudaInstallationDetector::CudaInstallationDetector(
62     const Driver &D, const llvm::Triple &HostTriple,
63     const llvm::opt::ArgList &Args)
64     : D(D) {
65   struct Candidate {
66     std::string Path;
67     bool StrictChecking;
68 
69     Candidate(std::string Path, bool StrictChecking = false)
70         : Path(Path), StrictChecking(StrictChecking) {}
71   };
72   SmallVector<Candidate, 4> Candidates;
73 
74   // In decreasing order so we prefer newer versions to older versions.
75   std::initializer_list<const char *> Versions = {"8.0", "7.5", "7.0"};
76 
77   if (Args.hasArg(clang::driver::options::OPT_cuda_path_EQ)) {
78     Candidates.emplace_back(
79         Args.getLastArgValue(clang::driver::options::OPT_cuda_path_EQ).str());
80   } else if (HostTriple.isOSWindows()) {
81     for (const char *Ver : Versions)
82       Candidates.emplace_back(
83           D.SysRoot + "/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v" +
84           Ver);
85   } else {
86     if (!Args.hasArg(clang::driver::options::OPT_cuda_path_ignore_env)) {
87       // Try to find ptxas binary. If the executable is located in a directory
88       // called 'bin/', its parent directory might be a good guess for a valid
89       // CUDA installation.
90       // However, some distributions might installs 'ptxas' to /usr/bin. In that
91       // case the candidate would be '/usr' which passes the following checks
92       // because '/usr/include' exists as well. To avoid this case, we always
93       // check for the directory potentially containing files for libdevice,
94       // even if the user passes -nocudalib.
95       if (llvm::ErrorOr<std::string> ptxas =
96               llvm::sys::findProgramByName("ptxas")) {
97         SmallString<256> ptxasAbsolutePath;
98         llvm::sys::fs::real_path(*ptxas, ptxasAbsolutePath);
99 
100         StringRef ptxasDir = llvm::sys::path::parent_path(ptxasAbsolutePath);
101         if (llvm::sys::path::filename(ptxasDir) == "bin")
102           Candidates.emplace_back(
103               std::string(llvm::sys::path::parent_path(ptxasDir)),
104               /*StrictChecking=*/true);
105       }
106     }
107 
108     Candidates.emplace_back(D.SysRoot + "/usr/local/cuda");
109     for (const char *Ver : Versions)
110       Candidates.emplace_back(D.SysRoot + "/usr/local/cuda-" + Ver);
111 
112     Distro Dist(D.getVFS(), llvm::Triple(llvm::sys::getProcessTriple()));
113     if (Dist.IsDebian() || Dist.IsUbuntu())
114       // Special case for Debian to have nvidia-cuda-toolkit work
115       // out of the box. More info on http://bugs.debian.org/882505
116       Candidates.emplace_back(D.SysRoot + "/usr/lib/cuda");
117   }
118 
119   bool NoCudaLib = Args.hasArg(options::OPT_nogpulib);
120 
121   for (const auto &Candidate : Candidates) {
122     InstallPath = Candidate.Path;
123     if (InstallPath.empty() || !D.getVFS().exists(InstallPath))
124       continue;
125 
126     BinPath = InstallPath + "/bin";
127     IncludePath = InstallPath + "/include";
128     LibDevicePath = InstallPath + "/nvvm/libdevice";
129 
130     auto &FS = D.getVFS();
131     if (!(FS.exists(IncludePath) && FS.exists(BinPath)))
132       continue;
133     bool CheckLibDevice = (!NoCudaLib || Candidate.StrictChecking);
134     if (CheckLibDevice && !FS.exists(LibDevicePath))
135       continue;
136 
137     // On Linux, we have both lib and lib64 directories, and we need to choose
138     // based on our triple.  On MacOS, we have only a lib directory.
139     //
140     // It's sufficient for our purposes to be flexible: If both lib and lib64
141     // exist, we choose whichever one matches our triple.  Otherwise, if only
142     // lib exists, we use it.
143     if (HostTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64"))
144       LibPath = InstallPath + "/lib64";
145     else if (FS.exists(InstallPath + "/lib"))
146       LibPath = InstallPath + "/lib";
147     else
148       continue;
149 
150     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
151         FS.getBufferForFile(InstallPath + "/version.txt");
152     if (!VersionFile) {
153       // CUDA 7.0 doesn't have a version.txt, so guess that's our version if
154       // version.txt isn't present.
155       Version = CudaVersion::CUDA_70;
156     } else {
157       ParseCudaVersionFile((*VersionFile)->getBuffer());
158     }
159 
160     if (Version >= CudaVersion::CUDA_90) {
161       // CUDA-9+ uses single libdevice file for all GPU variants.
162       std::string FilePath = LibDevicePath + "/libdevice.10.bc";
163       if (FS.exists(FilePath)) {
164         for (const char *GpuArchName :
165              {"sm_30", "sm_32", "sm_35", "sm_37", "sm_50", "sm_52", "sm_53",
166               "sm_60", "sm_61", "sm_62", "sm_70", "sm_72", "sm_75"}) {
167           const CudaArch GpuArch = StringToCudaArch(GpuArchName);
168           if (Version >= MinVersionForCudaArch(GpuArch) &&
169               Version <= MaxVersionForCudaArch(GpuArch))
170             LibDeviceMap[GpuArchName] = FilePath;
171         }
172       }
173     } else {
174       std::error_code EC;
175       for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE;
176            !EC && LI != LE; LI = LI.increment(EC)) {
177         StringRef FilePath = LI->path();
178         StringRef FileName = llvm::sys::path::filename(FilePath);
179         // Process all bitcode filenames that look like
180         // libdevice.compute_XX.YY.bc
181         const StringRef LibDeviceName = "libdevice.";
182         if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
183           continue;
184         StringRef GpuArch = FileName.slice(
185             LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
186         LibDeviceMap[GpuArch] = FilePath.str();
187         // Insert map entries for specific devices with this compute
188         // capability. NVCC's choice of the libdevice library version is
189         // rather peculiar and depends on the CUDA version.
190         if (GpuArch == "compute_20") {
191           LibDeviceMap["sm_20"] = std::string(FilePath);
192           LibDeviceMap["sm_21"] = std::string(FilePath);
193           LibDeviceMap["sm_32"] = std::string(FilePath);
194         } else if (GpuArch == "compute_30") {
195           LibDeviceMap["sm_30"] = std::string(FilePath);
196           if (Version < CudaVersion::CUDA_80) {
197             LibDeviceMap["sm_50"] = std::string(FilePath);
198             LibDeviceMap["sm_52"] = std::string(FilePath);
199             LibDeviceMap["sm_53"] = std::string(FilePath);
200           }
201           LibDeviceMap["sm_60"] = std::string(FilePath);
202           LibDeviceMap["sm_61"] = std::string(FilePath);
203           LibDeviceMap["sm_62"] = std::string(FilePath);
204         } else if (GpuArch == "compute_35") {
205           LibDeviceMap["sm_35"] = std::string(FilePath);
206           LibDeviceMap["sm_37"] = std::string(FilePath);
207         } else if (GpuArch == "compute_50") {
208           if (Version >= CudaVersion::CUDA_80) {
209             LibDeviceMap["sm_50"] = std::string(FilePath);
210             LibDeviceMap["sm_52"] = std::string(FilePath);
211             LibDeviceMap["sm_53"] = std::string(FilePath);
212           }
213         }
214       }
215     }
216 
217     // Check that we have found at least one libdevice that we can link in if
218     // -nocudalib hasn't been specified.
219     if (LibDeviceMap.empty() && !NoCudaLib)
220       continue;
221 
222     IsValid = true;
223     break;
224   }
225 }
226 
227 void CudaInstallationDetector::AddCudaIncludeArgs(
228     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
229   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
230     // Add cuda_wrappers/* to our system include path.  This lets us wrap
231     // standard library headers.
232     SmallString<128> P(D.ResourceDir);
233     llvm::sys::path::append(P, "include");
234     llvm::sys::path::append(P, "cuda_wrappers");
235     CC1Args.push_back("-internal-isystem");
236     CC1Args.push_back(DriverArgs.MakeArgString(P));
237   }
238 
239   if (DriverArgs.hasArg(options::OPT_nocudainc))
240     return;
241 
242   if (!isValid()) {
243     D.Diag(diag::err_drv_no_cuda_installation);
244     return;
245   }
246 
247   CC1Args.push_back("-internal-isystem");
248   CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
249   CC1Args.push_back("-include");
250   CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
251 }
252 
253 void CudaInstallationDetector::CheckCudaVersionSupportsArch(
254     CudaArch Arch) const {
255   if (Arch == CudaArch::UNKNOWN || Version == CudaVersion::UNKNOWN ||
256       ArchsWithBadVersion.count(Arch) > 0)
257     return;
258 
259   auto MinVersion = MinVersionForCudaArch(Arch);
260   auto MaxVersion = MaxVersionForCudaArch(Arch);
261   if (Version < MinVersion || Version > MaxVersion) {
262     ArchsWithBadVersion.insert(Arch);
263     D.Diag(diag::err_drv_cuda_version_unsupported)
264         << CudaArchToString(Arch) << CudaVersionToString(MinVersion)
265         << CudaVersionToString(MaxVersion) << InstallPath
266         << CudaVersionToString(Version);
267   }
268 }
269 
270 void CudaInstallationDetector::print(raw_ostream &OS) const {
271   if (isValid())
272     OS << "Found CUDA installation: " << InstallPath << ", version "
273        << CudaVersionToString(Version) << "\n";
274 }
275 
276 namespace {
277 /// Debug info level for the NVPTX devices. We may need to emit different debug
278 /// info level for the host and for the device itselfi. This type controls
279 /// emission of the debug info for the devices. It either prohibits disable info
280 /// emission completely, or emits debug directives only, or emits same debug
281 /// info as for the host.
282 enum DeviceDebugInfoLevel {
283   DisableDebugInfo,        /// Do not emit debug info for the devices.
284   DebugDirectivesOnly,     /// Emit only debug directives.
285   EmitSameDebugInfoAsHost, /// Use the same debug info level just like for the
286                            /// host.
287 };
288 } // anonymous namespace
289 
290 /// Define debug info level for the NVPTX devices. If the debug info for both
291 /// the host and device are disabled (-g0/-ggdb0 or no debug options at all). If
292 /// only debug directives are requested for the both host and device
293 /// (-gline-directvies-only), or the debug info only for the device is disabled
294 /// (optimization is on and --cuda-noopt-device-debug was not specified), the
295 /// debug directves only must be emitted for the device. Otherwise, use the same
296 /// debug info level just like for the host (with the limitations of only
297 /// supported DWARF2 standard).
298 static DeviceDebugInfoLevel mustEmitDebugInfo(const ArgList &Args) {
299   const Arg *A = Args.getLastArg(options::OPT_O_Group);
300   bool IsDebugEnabled = !A || A->getOption().matches(options::OPT_O0) ||
301                         Args.hasFlag(options::OPT_cuda_noopt_device_debug,
302                                      options::OPT_no_cuda_noopt_device_debug,
303                                      /*Default=*/false);
304   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
305     const Option &Opt = A->getOption();
306     if (Opt.matches(options::OPT_gN_Group)) {
307       if (Opt.matches(options::OPT_g0) || Opt.matches(options::OPT_ggdb0))
308         return DisableDebugInfo;
309       if (Opt.matches(options::OPT_gline_directives_only))
310         return DebugDirectivesOnly;
311     }
312     return IsDebugEnabled ? EmitSameDebugInfoAsHost : DebugDirectivesOnly;
313   }
314   return DisableDebugInfo;
315 }
316 
317 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
318                                     const InputInfo &Output,
319                                     const InputInfoList &Inputs,
320                                     const ArgList &Args,
321                                     const char *LinkingOutput) const {
322   const auto &TC =
323       static_cast<const toolchains::CudaToolChain &>(getToolChain());
324   assert(TC.getTriple().isNVPTX() && "Wrong platform");
325 
326   StringRef GPUArchName;
327   // If this is an OpenMP action we need to extract the device architecture
328   // from the -march=arch option. This option may come from -Xopenmp-target
329   // flag or the default value.
330   if (JA.isDeviceOffloading(Action::OFK_OpenMP)) {
331     GPUArchName = Args.getLastArgValue(options::OPT_march_EQ);
332     assert(!GPUArchName.empty() && "Must have an architecture passed in.");
333   } else
334     GPUArchName = JA.getOffloadingArch();
335 
336   // Obtain architecture from the action.
337   CudaArch gpu_arch = StringToCudaArch(GPUArchName);
338   assert(gpu_arch != CudaArch::UNKNOWN &&
339          "Device action expected to have an architecture.");
340 
341   // Check that our installation's ptxas supports gpu_arch.
342   if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
343     TC.CudaInstallation.CheckCudaVersionSupportsArch(gpu_arch);
344   }
345 
346   ArgStringList CmdArgs;
347   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
348   DeviceDebugInfoLevel DIKind = mustEmitDebugInfo(Args);
349   if (DIKind == EmitSameDebugInfoAsHost) {
350     // ptxas does not accept -g option if optimization is enabled, so
351     // we ignore the compiler's -O* options if we want debug info.
352     CmdArgs.push_back("-g");
353     CmdArgs.push_back("--dont-merge-basicblocks");
354     CmdArgs.push_back("--return-at-end");
355   } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
356     // Map the -O we received to -O{0,1,2,3}.
357     //
358     // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
359     // default, so it may correspond more closely to the spirit of clang -O2.
360 
361     // -O3 seems like the least-bad option when -Osomething is specified to
362     // clang but it isn't handled below.
363     StringRef OOpt = "3";
364     if (A->getOption().matches(options::OPT_O4) ||
365         A->getOption().matches(options::OPT_Ofast))
366       OOpt = "3";
367     else if (A->getOption().matches(options::OPT_O0))
368       OOpt = "0";
369     else if (A->getOption().matches(options::OPT_O)) {
370       // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
371       OOpt = llvm::StringSwitch<const char *>(A->getValue())
372                  .Case("1", "1")
373                  .Case("2", "2")
374                  .Case("3", "3")
375                  .Case("s", "2")
376                  .Case("z", "2")
377                  .Default("2");
378     }
379     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
380   } else {
381     // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
382     // to no optimizations, but ptxas's default is -O3.
383     CmdArgs.push_back("-O0");
384   }
385   if (DIKind == DebugDirectivesOnly)
386     CmdArgs.push_back("-lineinfo");
387 
388   // Pass -v to ptxas if it was passed to the driver.
389   if (Args.hasArg(options::OPT_v))
390     CmdArgs.push_back("-v");
391 
392   CmdArgs.push_back("--gpu-name");
393   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
394   CmdArgs.push_back("--output-file");
395   CmdArgs.push_back(Args.MakeArgString(TC.getInputFilename(Output)));
396   for (const auto& II : Inputs)
397     CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
398 
399   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
400     CmdArgs.push_back(Args.MakeArgString(A));
401 
402   bool Relocatable = false;
403   if (JA.isOffloading(Action::OFK_OpenMP))
404     // In OpenMP we need to generate relocatable code.
405     Relocatable = Args.hasFlag(options::OPT_fopenmp_relocatable_target,
406                                options::OPT_fnoopenmp_relocatable_target,
407                                /*Default=*/true);
408   else if (JA.isOffloading(Action::OFK_Cuda))
409     Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
410                                options::OPT_fno_gpu_rdc, /*Default=*/false);
411 
412   if (Relocatable)
413     CmdArgs.push_back("-c");
414 
415   const char *Exec;
416   if (Arg *A = Args.getLastArg(options::OPT_ptxas_path_EQ))
417     Exec = A->getValue();
418   else
419     Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
420   C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
421 }
422 
423 static bool shouldIncludePTX(const ArgList &Args, const char *gpu_arch) {
424   bool includePTX = true;
425   for (Arg *A : Args) {
426     if (!(A->getOption().matches(options::OPT_cuda_include_ptx_EQ) ||
427           A->getOption().matches(options::OPT_no_cuda_include_ptx_EQ)))
428       continue;
429     A->claim();
430     const StringRef ArchStr = A->getValue();
431     if (ArchStr == "all" || ArchStr == gpu_arch) {
432       includePTX = A->getOption().matches(options::OPT_cuda_include_ptx_EQ);
433       continue;
434     }
435   }
436   return includePTX;
437 }
438 
439 // All inputs to this linker must be from CudaDeviceActions, as we need to look
440 // at the Inputs' Actions in order to figure out which GPU architecture they
441 // correspond to.
442 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
443                                  const InputInfo &Output,
444                                  const InputInfoList &Inputs,
445                                  const ArgList &Args,
446                                  const char *LinkingOutput) const {
447   const auto &TC =
448       static_cast<const toolchains::CudaToolChain &>(getToolChain());
449   assert(TC.getTriple().isNVPTX() && "Wrong platform");
450 
451   ArgStringList CmdArgs;
452   if (TC.CudaInstallation.version() <= CudaVersion::CUDA_100)
453     CmdArgs.push_back("--cuda");
454   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
455   CmdArgs.push_back(Args.MakeArgString("--create"));
456   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
457   if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
458     CmdArgs.push_back("-g");
459 
460   for (const auto& II : Inputs) {
461     auto *A = II.getAction();
462     assert(A->getInputs().size() == 1 &&
463            "Device offload action is expected to have a single input");
464     const char *gpu_arch_str = A->getOffloadingArch();
465     assert(gpu_arch_str &&
466            "Device action expected to have associated a GPU architecture!");
467     CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
468 
469     if (II.getType() == types::TY_PP_Asm &&
470         !shouldIncludePTX(Args, gpu_arch_str))
471       continue;
472     // We need to pass an Arch of the form "sm_XX" for cubin files and
473     // "compute_XX" for ptx.
474     const char *Arch =
475         (II.getType() == types::TY_PP_Asm)
476             ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
477             : gpu_arch_str;
478     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
479                                          Arch + ",file=" + II.getFilename()));
480   }
481 
482   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
483     CmdArgs.push_back(Args.MakeArgString(A));
484 
485   const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
486   C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
487 }
488 
489 void NVPTX::OpenMPLinker::ConstructJob(Compilation &C, const JobAction &JA,
490                                        const InputInfo &Output,
491                                        const InputInfoList &Inputs,
492                                        const ArgList &Args,
493                                        const char *LinkingOutput) const {
494   const auto &TC =
495       static_cast<const toolchains::CudaToolChain &>(getToolChain());
496   assert(TC.getTriple().isNVPTX() && "Wrong platform");
497 
498   ArgStringList CmdArgs;
499 
500   // OpenMP uses nvlink to link cubin files. The result will be embedded in the
501   // host binary by the host linker.
502   assert(!JA.isHostOffloading(Action::OFK_OpenMP) &&
503          "CUDA toolchain not expected for an OpenMP host device.");
504 
505   if (Output.isFilename()) {
506     CmdArgs.push_back("-o");
507     CmdArgs.push_back(Output.getFilename());
508   } else
509     assert(Output.isNothing() && "Invalid output.");
510   if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
511     CmdArgs.push_back("-g");
512 
513   if (Args.hasArg(options::OPT_v))
514     CmdArgs.push_back("-v");
515 
516   StringRef GPUArch =
517       Args.getLastArgValue(options::OPT_march_EQ);
518   assert(!GPUArch.empty() && "At least one GPU Arch required for ptxas.");
519 
520   CmdArgs.push_back("-arch");
521   CmdArgs.push_back(Args.MakeArgString(GPUArch));
522 
523   // Assume that the directory specified with --libomptarget_nvptx_path
524   // contains the static library libomptarget-nvptx.a.
525   if (const Arg *A = Args.getLastArg(options::OPT_libomptarget_nvptx_path_EQ))
526     CmdArgs.push_back(Args.MakeArgString(Twine("-L") + A->getValue()));
527 
528   // Add paths specified in LIBRARY_PATH environment variable as -L options.
529   addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
530 
531   // Add paths for the default clang library path.
532   SmallString<256> DefaultLibPath =
533       llvm::sys::path::parent_path(TC.getDriver().Dir);
534   llvm::sys::path::append(DefaultLibPath, "lib" CLANG_LIBDIR_SUFFIX);
535   CmdArgs.push_back(Args.MakeArgString(Twine("-L") + DefaultLibPath));
536 
537   // Add linking against library implementing OpenMP calls on NVPTX target.
538   CmdArgs.push_back("-lomptarget-nvptx");
539 
540   for (const auto &II : Inputs) {
541     if (II.getType() == types::TY_LLVM_IR ||
542         II.getType() == types::TY_LTO_IR ||
543         II.getType() == types::TY_LTO_BC ||
544         II.getType() == types::TY_LLVM_BC) {
545       C.getDriver().Diag(diag::err_drv_no_linker_llvm_support)
546           << getToolChain().getTripleString();
547       continue;
548     }
549 
550     // Currently, we only pass the input files to the linker, we do not pass
551     // any libraries that may be valid only for the host.
552     if (!II.isFilename())
553       continue;
554 
555     const char *CubinF = C.addTempFile(
556         C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
557 
558     CmdArgs.push_back(CubinF);
559   }
560 
561   const char *Exec =
562       Args.MakeArgString(getToolChain().GetProgramPath("nvlink"));
563   C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
564 }
565 
566 /// CUDA toolchain.  Our assembler is ptxas, and our "linker" is fatbinary,
567 /// which isn't properly a linker but nonetheless performs the step of stitching
568 /// together object files from the assembler into a single blob.
569 
570 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
571                              const ToolChain &HostTC, const ArgList &Args,
572                              const Action::OffloadKind OK)
573     : ToolChain(D, Triple, Args), HostTC(HostTC),
574       CudaInstallation(D, HostTC.getTriple(), Args), OK(OK) {
575   if (CudaInstallation.isValid()) {
576     CudaInstallation.WarnIfUnsupportedVersion();
577     getProgramPaths().push_back(std::string(CudaInstallation.getBinPath()));
578   }
579   // Lookup binaries into the driver directory, this is used to
580   // discover the clang-offload-bundler executable.
581   getProgramPaths().push_back(getDriver().Dir);
582 }
583 
584 std::string CudaToolChain::getInputFilename(const InputInfo &Input) const {
585   // Only object files are changed, for example assembly files keep their .s
586   // extensions. CUDA also continues to use .o as they don't use nvlink but
587   // fatbinary.
588   if (!(OK == Action::OFK_OpenMP && Input.getType() == types::TY_Object))
589     return ToolChain::getInputFilename(Input);
590 
591   // Replace extension for object files with cubin because nvlink relies on
592   // these particular file names.
593   SmallString<256> Filename(ToolChain::getInputFilename(Input));
594   llvm::sys::path::replace_extension(Filename, "cubin");
595   return std::string(Filename.str());
596 }
597 
598 void CudaToolChain::addClangTargetOptions(
599     const llvm::opt::ArgList &DriverArgs,
600     llvm::opt::ArgStringList &CC1Args,
601     Action::OffloadKind DeviceOffloadingKind) const {
602   HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
603 
604   StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
605   assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
606   assert((DeviceOffloadingKind == Action::OFK_OpenMP ||
607           DeviceOffloadingKind == Action::OFK_Cuda) &&
608          "Only OpenMP or CUDA offloading kinds are supported for NVIDIA GPUs.");
609 
610   if (DeviceOffloadingKind == Action::OFK_Cuda) {
611     CC1Args.push_back("-fcuda-is-device");
612 
613     if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
614                            options::OPT_fno_cuda_approx_transcendentals, false))
615       CC1Args.push_back("-fcuda-approx-transcendentals");
616 
617     if (DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
618                            false))
619       CC1Args.push_back("-fgpu-rdc");
620   }
621 
622   if (DriverArgs.hasArg(options::OPT_nogpulib))
623     return;
624 
625   std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(GpuArch);
626 
627   if (LibDeviceFile.empty()) {
628     if (DeviceOffloadingKind == Action::OFK_OpenMP &&
629         DriverArgs.hasArg(options::OPT_S))
630       return;
631 
632     getDriver().Diag(diag::err_drv_no_cuda_libdevice) << GpuArch;
633     return;
634   }
635 
636   CC1Args.push_back("-mlink-builtin-bitcode");
637   CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
638 
639   // New CUDA versions often introduce new instructions that are only supported
640   // by new PTX version, so we need to raise PTX level to enable them in NVPTX
641   // back-end.
642   const char *PtxFeature = nullptr;
643   switch(CudaInstallation.version()) {
644     case CudaVersion::CUDA_101:
645       PtxFeature = "+ptx64";
646       break;
647     case CudaVersion::CUDA_100:
648       PtxFeature = "+ptx63";
649       break;
650     case CudaVersion::CUDA_92:
651       PtxFeature = "+ptx61";
652       break;
653     case CudaVersion::CUDA_91:
654       PtxFeature = "+ptx61";
655       break;
656     case CudaVersion::CUDA_90:
657       PtxFeature = "+ptx60";
658       break;
659     default:
660       PtxFeature = "+ptx42";
661   }
662   CC1Args.append({"-target-feature", PtxFeature});
663   if (DriverArgs.hasFlag(options::OPT_fcuda_short_ptr,
664                          options::OPT_fno_cuda_short_ptr, false))
665     CC1Args.append({"-mllvm", "--nvptx-short-ptr"});
666 
667   if (CudaInstallation.version() >= CudaVersion::UNKNOWN)
668     CC1Args.push_back(DriverArgs.MakeArgString(
669         Twine("-target-sdk-version=") +
670         CudaVersionToString(CudaInstallation.version())));
671 
672   if (DeviceOffloadingKind == Action::OFK_OpenMP) {
673     SmallVector<StringRef, 8> LibraryPaths;
674     if (const Arg *A = DriverArgs.getLastArg(options::OPT_libomptarget_nvptx_path_EQ))
675       LibraryPaths.push_back(A->getValue());
676 
677     // Add user defined library paths from LIBRARY_PATH.
678     llvm::Optional<std::string> LibPath =
679         llvm::sys::Process::GetEnv("LIBRARY_PATH");
680     if (LibPath) {
681       SmallVector<StringRef, 8> Frags;
682       const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
683       llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
684       for (StringRef Path : Frags)
685         LibraryPaths.emplace_back(Path.trim());
686     }
687 
688     // Add path to lib / lib64 folder.
689     SmallString<256> DefaultLibPath =
690         llvm::sys::path::parent_path(getDriver().Dir);
691     llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
692     LibraryPaths.emplace_back(DefaultLibPath.c_str());
693 
694     std::string LibOmpTargetName =
695       "libomptarget-nvptx-" + GpuArch.str() + ".bc";
696     bool FoundBCLibrary = false;
697     for (StringRef LibraryPath : LibraryPaths) {
698       SmallString<128> LibOmpTargetFile(LibraryPath);
699       llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
700       if (llvm::sys::fs::exists(LibOmpTargetFile)) {
701         CC1Args.push_back("-mlink-builtin-bitcode");
702         CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
703         FoundBCLibrary = true;
704         break;
705       }
706     }
707     if (!FoundBCLibrary)
708       getDriver().Diag(diag::warn_drv_omp_offload_target_missingbcruntime)
709           << LibOmpTargetName;
710   }
711 }
712 
713 llvm::DenormalMode CudaToolChain::getDefaultDenormalModeForType(
714     const llvm::opt::ArgList &DriverArgs, Action::OffloadKind DeviceOffloadKind,
715     const llvm::fltSemantics *FPType) const {
716   if (DeviceOffloadKind == Action::OFK_Cuda) {
717     if (FPType && FPType == &llvm::APFloat::IEEEsingle() &&
718         DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
719                            options::OPT_fno_cuda_flush_denormals_to_zero,
720                            false))
721       return llvm::DenormalMode::getPreserveSign();
722   }
723 
724   assert(DeviceOffloadKind != Action::OFK_Host);
725   return llvm::DenormalMode::getIEEE();
726 }
727 
728 bool CudaToolChain::supportsDebugInfoOption(const llvm::opt::Arg *A) const {
729   const Option &O = A->getOption();
730   return (O.matches(options::OPT_gN_Group) &&
731           !O.matches(options::OPT_gmodules)) ||
732          O.matches(options::OPT_g_Flag) ||
733          O.matches(options::OPT_ggdbN_Group) || O.matches(options::OPT_ggdb) ||
734          O.matches(options::OPT_gdwarf) || O.matches(options::OPT_gdwarf_2) ||
735          O.matches(options::OPT_gdwarf_3) || O.matches(options::OPT_gdwarf_4) ||
736          O.matches(options::OPT_gdwarf_5) ||
737          O.matches(options::OPT_gcolumn_info);
738 }
739 
740 void CudaToolChain::adjustDebugInfoKind(
741     codegenoptions::DebugInfoKind &DebugInfoKind, const ArgList &Args) const {
742   switch (mustEmitDebugInfo(Args)) {
743   case DisableDebugInfo:
744     DebugInfoKind = codegenoptions::NoDebugInfo;
745     break;
746   case DebugDirectivesOnly:
747     DebugInfoKind = codegenoptions::DebugDirectivesOnly;
748     break;
749   case EmitSameDebugInfoAsHost:
750     // Use same debug info level as the host.
751     break;
752   }
753 }
754 
755 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
756                                        ArgStringList &CC1Args) const {
757   // Check our CUDA version if we're going to include the CUDA headers.
758   if (!DriverArgs.hasArg(options::OPT_nocudainc) &&
759       !DriverArgs.hasArg(options::OPT_no_cuda_version_check)) {
760     StringRef Arch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
761     assert(!Arch.empty() && "Must have an explicit GPU arch.");
762     CudaInstallation.CheckCudaVersionSupportsArch(StringToCudaArch(Arch));
763   }
764   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
765 }
766 
767 llvm::opt::DerivedArgList *
768 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
769                              StringRef BoundArch,
770                              Action::OffloadKind DeviceOffloadKind) const {
771   DerivedArgList *DAL =
772       HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
773   if (!DAL)
774     DAL = new DerivedArgList(Args.getBaseArgs());
775 
776   const OptTable &Opts = getDriver().getOpts();
777 
778   // For OpenMP device offloading, append derived arguments. Make sure
779   // flags are not duplicated.
780   // Also append the compute capability.
781   if (DeviceOffloadKind == Action::OFK_OpenMP) {
782     for (Arg *A : Args) {
783       bool IsDuplicate = false;
784       for (Arg *DALArg : *DAL) {
785         if (A == DALArg) {
786           IsDuplicate = true;
787           break;
788         }
789       }
790       if (!IsDuplicate)
791         DAL->append(A);
792     }
793 
794     StringRef Arch = DAL->getLastArgValue(options::OPT_march_EQ);
795     if (Arch.empty())
796       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ),
797                         CLANG_OPENMP_NVPTX_DEFAULT_ARCH);
798 
799     return DAL;
800   }
801 
802   for (Arg *A : Args) {
803     if (A->getOption().matches(options::OPT_Xarch__)) {
804       // Skip this argument unless the architecture matches BoundArch
805       if (BoundArch.empty() || A->getValue(0) != BoundArch)
806         continue;
807 
808       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
809       unsigned Prev = Index;
810       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
811 
812       // If the argument parsing failed or more than one argument was
813       // consumed, the -Xarch_ argument's parameter tried to consume
814       // extra arguments. Emit an error and ignore.
815       //
816       // We also want to disallow any options which would alter the
817       // driver behavior; that isn't going to work in our model. We
818       // use isDriverOption() as an approximation, although things
819       // like -O4 are going to slip through.
820       if (!XarchArg || Index > Prev + 1) {
821         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
822             << A->getAsString(Args);
823         continue;
824       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
825         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
826             << A->getAsString(Args);
827         continue;
828       }
829       XarchArg->setBaseArg(A);
830       A = XarchArg.release();
831       DAL->AddSynthesizedArg(A);
832     }
833     DAL->append(A);
834   }
835 
836   if (!BoundArch.empty()) {
837     DAL->eraseArg(options::OPT_march_EQ);
838     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
839   }
840   return DAL;
841 }
842 
843 Tool *CudaToolChain::buildAssembler() const {
844   return new tools::NVPTX::Assembler(*this);
845 }
846 
847 Tool *CudaToolChain::buildLinker() const {
848   if (OK == Action::OFK_OpenMP)
849     return new tools::NVPTX::OpenMPLinker(*this);
850   return new tools::NVPTX::Linker(*this);
851 }
852 
853 void CudaToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
854   HostTC.addClangWarningOptions(CC1Args);
855 }
856 
857 ToolChain::CXXStdlibType
858 CudaToolChain::GetCXXStdlibType(const ArgList &Args) const {
859   return HostTC.GetCXXStdlibType(Args);
860 }
861 
862 void CudaToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
863                                               ArgStringList &CC1Args) const {
864   HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
865 }
866 
867 void CudaToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
868                                                  ArgStringList &CC1Args) const {
869   HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
870 }
871 
872 void CudaToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
873                                         ArgStringList &CC1Args) const {
874   HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
875 }
876 
877 SanitizerMask CudaToolChain::getSupportedSanitizers() const {
878   // The CudaToolChain only supports sanitizers in the sense that it allows
879   // sanitizer arguments on the command line if they are supported by the host
880   // toolchain. The CudaToolChain will actually ignore any command line
881   // arguments for any of these "supported" sanitizers. That means that no
882   // sanitization of device code is actually supported at this time.
883   //
884   // This behavior is necessary because the host and device toolchains
885   // invocations often share the command line, so the device toolchain must
886   // tolerate flags meant only for the host toolchain.
887   return HostTC.getSupportedSanitizers();
888 }
889 
890 VersionTuple CudaToolChain::computeMSVCVersion(const Driver *D,
891                                                const ArgList &Args) const {
892   return HostTC.computeMSVCVersion(D, Args);
893 }
894