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 "clang/Basic/Cuda.h"
12 #include "clang/Config/config.h"
13 #include "clang/Driver/Compilation.h"
14 #include "clang/Driver/Distro.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/InputInfo.h"
18 #include "clang/Driver/Options.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Option/ArgList.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/FormatAdapters.h"
23 #include "llvm/Support/FormatVariadic.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/Process.h"
26 #include "llvm/Support/Program.h"
27 #include "llvm/Support/VirtualFileSystem.h"
28 #include "llvm/TargetParser/Host.h"
29 #include "llvm/TargetParser/TargetParser.h"
30 #include <system_error>
31 
32 using namespace clang::driver;
33 using namespace clang::driver::toolchains;
34 using namespace clang::driver::tools;
35 using namespace clang;
36 using namespace llvm::opt;
37 
38 namespace {
39 
40 CudaVersion getCudaVersion(uint32_t raw_version) {
41   if (raw_version < 7050)
42     return CudaVersion::CUDA_70;
43   if (raw_version < 8000)
44     return CudaVersion::CUDA_75;
45   if (raw_version < 9000)
46     return CudaVersion::CUDA_80;
47   if (raw_version < 9010)
48     return CudaVersion::CUDA_90;
49   if (raw_version < 9020)
50     return CudaVersion::CUDA_91;
51   if (raw_version < 10000)
52     return CudaVersion::CUDA_92;
53   if (raw_version < 10010)
54     return CudaVersion::CUDA_100;
55   if (raw_version < 10020)
56     return CudaVersion::CUDA_101;
57   if (raw_version < 11000)
58     return CudaVersion::CUDA_102;
59   if (raw_version < 11010)
60     return CudaVersion::CUDA_110;
61   if (raw_version < 11020)
62     return CudaVersion::CUDA_111;
63   if (raw_version < 11030)
64     return CudaVersion::CUDA_112;
65   if (raw_version < 11040)
66     return CudaVersion::CUDA_113;
67   if (raw_version < 11050)
68     return CudaVersion::CUDA_114;
69   if (raw_version < 11060)
70     return CudaVersion::CUDA_115;
71   if (raw_version < 11070)
72     return CudaVersion::CUDA_116;
73   if (raw_version < 11080)
74     return CudaVersion::CUDA_117;
75   if (raw_version < 11090)
76     return CudaVersion::CUDA_118;
77   if (raw_version < 12010)
78     return CudaVersion::CUDA_120;
79   if (raw_version < 12020)
80     return CudaVersion::CUDA_121;
81   return CudaVersion::NEW;
82 }
83 
84 CudaVersion parseCudaHFile(llvm::StringRef Input) {
85   // Helper lambda which skips the words if the line starts with them or returns
86   // std::nullopt otherwise.
87   auto StartsWithWords =
88       [](llvm::StringRef Line,
89          const SmallVector<StringRef, 3> words) -> std::optional<StringRef> {
90     for (StringRef word : words) {
91       if (!Line.consume_front(word))
92         return {};
93       Line = Line.ltrim();
94     }
95     return Line;
96   };
97 
98   Input = Input.ltrim();
99   while (!Input.empty()) {
100     if (auto Line =
101             StartsWithWords(Input.ltrim(), {"#", "define", "CUDA_VERSION"})) {
102       uint32_t RawVersion;
103       Line->consumeInteger(10, RawVersion);
104       return getCudaVersion(RawVersion);
105     }
106     // Find next non-empty line.
107     Input = Input.drop_front(Input.find_first_of("\n\r")).ltrim();
108   }
109   return CudaVersion::UNKNOWN;
110 }
111 } // namespace
112 
113 void CudaInstallationDetector::WarnIfUnsupportedVersion() {
114   if (Version > CudaVersion::PARTIALLY_SUPPORTED) {
115     std::string VersionString = CudaVersionToString(Version);
116     if (!VersionString.empty())
117       VersionString.insert(0, " ");
118     D.Diag(diag::warn_drv_new_cuda_version)
119         << VersionString
120         << (CudaVersion::PARTIALLY_SUPPORTED != CudaVersion::FULLY_SUPPORTED)
121         << CudaVersionToString(CudaVersion::PARTIALLY_SUPPORTED);
122   } else if (Version > CudaVersion::FULLY_SUPPORTED)
123     D.Diag(diag::warn_drv_partially_supported_cuda_version)
124         << CudaVersionToString(Version);
125 }
126 
127 CudaInstallationDetector::CudaInstallationDetector(
128     const Driver &D, const llvm::Triple &HostTriple,
129     const llvm::opt::ArgList &Args)
130     : D(D) {
131   struct Candidate {
132     std::string Path;
133     bool StrictChecking;
134 
135     Candidate(std::string Path, bool StrictChecking = false)
136         : Path(Path), StrictChecking(StrictChecking) {}
137   };
138   SmallVector<Candidate, 4> Candidates;
139 
140   // In decreasing order so we prefer newer versions to older versions.
141   std::initializer_list<const char *> Versions = {"8.0", "7.5", "7.0"};
142   auto &FS = D.getVFS();
143 
144   if (Args.hasArg(clang::driver::options::OPT_cuda_path_EQ)) {
145     Candidates.emplace_back(
146         Args.getLastArgValue(clang::driver::options::OPT_cuda_path_EQ).str());
147   } else if (HostTriple.isOSWindows()) {
148     for (const char *Ver : Versions)
149       Candidates.emplace_back(
150           D.SysRoot + "/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v" +
151           Ver);
152   } else {
153     if (!Args.hasArg(clang::driver::options::OPT_cuda_path_ignore_env)) {
154       // Try to find ptxas binary. If the executable is located in a directory
155       // called 'bin/', its parent directory might be a good guess for a valid
156       // CUDA installation.
157       // However, some distributions might installs 'ptxas' to /usr/bin. In that
158       // case the candidate would be '/usr' which passes the following checks
159       // because '/usr/include' exists as well. To avoid this case, we always
160       // check for the directory potentially containing files for libdevice,
161       // even if the user passes -nocudalib.
162       if (llvm::ErrorOr<std::string> ptxas =
163               llvm::sys::findProgramByName("ptxas")) {
164         SmallString<256> ptxasAbsolutePath;
165         llvm::sys::fs::real_path(*ptxas, ptxasAbsolutePath);
166 
167         StringRef ptxasDir = llvm::sys::path::parent_path(ptxasAbsolutePath);
168         if (llvm::sys::path::filename(ptxasDir) == "bin")
169           Candidates.emplace_back(
170               std::string(llvm::sys::path::parent_path(ptxasDir)),
171               /*StrictChecking=*/true);
172       }
173     }
174 
175     Candidates.emplace_back(D.SysRoot + "/usr/local/cuda");
176     for (const char *Ver : Versions)
177       Candidates.emplace_back(D.SysRoot + "/usr/local/cuda-" + Ver);
178 
179     Distro Dist(FS, llvm::Triple(llvm::sys::getProcessTriple()));
180     if (Dist.IsDebian() || Dist.IsUbuntu())
181       // Special case for Debian to have nvidia-cuda-toolkit work
182       // out of the box. More info on http://bugs.debian.org/882505
183       Candidates.emplace_back(D.SysRoot + "/usr/lib/cuda");
184   }
185 
186   bool NoCudaLib = Args.hasArg(options::OPT_nogpulib);
187 
188   for (const auto &Candidate : Candidates) {
189     InstallPath = Candidate.Path;
190     if (InstallPath.empty() || !FS.exists(InstallPath))
191       continue;
192 
193     BinPath = InstallPath + "/bin";
194     IncludePath = InstallPath + "/include";
195     LibDevicePath = InstallPath + "/nvvm/libdevice";
196 
197     if (!(FS.exists(IncludePath) && FS.exists(BinPath)))
198       continue;
199     bool CheckLibDevice = (!NoCudaLib || Candidate.StrictChecking);
200     if (CheckLibDevice && !FS.exists(LibDevicePath))
201       continue;
202 
203     Version = CudaVersion::UNKNOWN;
204     if (auto CudaHFile = FS.getBufferForFile(InstallPath + "/include/cuda.h"))
205       Version = parseCudaHFile((*CudaHFile)->getBuffer());
206     // As the last resort, make an educated guess between CUDA-7.0, which had
207     // old-style libdevice bitcode, and an unknown recent CUDA version.
208     if (Version == CudaVersion::UNKNOWN) {
209       Version = FS.exists(LibDevicePath + "/libdevice.10.bc")
210                     ? CudaVersion::NEW
211                     : CudaVersion::CUDA_70;
212     }
213 
214     if (Version >= CudaVersion::CUDA_90) {
215       // CUDA-9+ uses single libdevice file for all GPU variants.
216       std::string FilePath = LibDevicePath + "/libdevice.10.bc";
217       if (FS.exists(FilePath)) {
218         for (int Arch = (int)CudaArch::SM_30, E = (int)CudaArch::LAST; Arch < E;
219              ++Arch) {
220           CudaArch GpuArch = static_cast<CudaArch>(Arch);
221           if (!IsNVIDIAGpuArch(GpuArch))
222             continue;
223           std::string GpuArchName(CudaArchToString(GpuArch));
224           LibDeviceMap[GpuArchName] = FilePath;
225         }
226       }
227     } else {
228       std::error_code EC;
229       for (llvm::vfs::directory_iterator LI = FS.dir_begin(LibDevicePath, EC),
230                                          LE;
231            !EC && LI != LE; LI = LI.increment(EC)) {
232         StringRef FilePath = LI->path();
233         StringRef FileName = llvm::sys::path::filename(FilePath);
234         // Process all bitcode filenames that look like
235         // libdevice.compute_XX.YY.bc
236         const StringRef LibDeviceName = "libdevice.";
237         if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
238           continue;
239         StringRef GpuArch = FileName.slice(
240             LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
241         LibDeviceMap[GpuArch] = FilePath.str();
242         // Insert map entries for specific devices with this compute
243         // capability. NVCC's choice of the libdevice library version is
244         // rather peculiar and depends on the CUDA version.
245         if (GpuArch == "compute_20") {
246           LibDeviceMap["sm_20"] = std::string(FilePath);
247           LibDeviceMap["sm_21"] = std::string(FilePath);
248           LibDeviceMap["sm_32"] = std::string(FilePath);
249         } else if (GpuArch == "compute_30") {
250           LibDeviceMap["sm_30"] = std::string(FilePath);
251           if (Version < CudaVersion::CUDA_80) {
252             LibDeviceMap["sm_50"] = std::string(FilePath);
253             LibDeviceMap["sm_52"] = std::string(FilePath);
254             LibDeviceMap["sm_53"] = std::string(FilePath);
255           }
256           LibDeviceMap["sm_60"] = std::string(FilePath);
257           LibDeviceMap["sm_61"] = std::string(FilePath);
258           LibDeviceMap["sm_62"] = std::string(FilePath);
259         } else if (GpuArch == "compute_35") {
260           LibDeviceMap["sm_35"] = std::string(FilePath);
261           LibDeviceMap["sm_37"] = std::string(FilePath);
262         } else if (GpuArch == "compute_50") {
263           if (Version >= CudaVersion::CUDA_80) {
264             LibDeviceMap["sm_50"] = std::string(FilePath);
265             LibDeviceMap["sm_52"] = std::string(FilePath);
266             LibDeviceMap["sm_53"] = std::string(FilePath);
267           }
268         }
269       }
270     }
271 
272     // Check that we have found at least one libdevice that we can link in if
273     // -nocudalib hasn't been specified.
274     if (LibDeviceMap.empty() && !NoCudaLib)
275       continue;
276 
277     IsValid = true;
278     break;
279   }
280 }
281 
282 void CudaInstallationDetector::AddCudaIncludeArgs(
283     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
284   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
285     // Add cuda_wrappers/* to our system include path.  This lets us wrap
286     // standard library headers.
287     SmallString<128> P(D.ResourceDir);
288     llvm::sys::path::append(P, "include");
289     llvm::sys::path::append(P, "cuda_wrappers");
290     CC1Args.push_back("-internal-isystem");
291     CC1Args.push_back(DriverArgs.MakeArgString(P));
292   }
293 
294   if (DriverArgs.hasArg(options::OPT_nogpuinc))
295     return;
296 
297   if (!isValid()) {
298     D.Diag(diag::err_drv_no_cuda_installation);
299     return;
300   }
301 
302   CC1Args.push_back("-include");
303   CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
304 }
305 
306 void CudaInstallationDetector::CheckCudaVersionSupportsArch(
307     CudaArch Arch) const {
308   if (Arch == CudaArch::UNKNOWN || Version == CudaVersion::UNKNOWN ||
309       ArchsWithBadVersion[(int)Arch])
310     return;
311 
312   auto MinVersion = MinVersionForCudaArch(Arch);
313   auto MaxVersion = MaxVersionForCudaArch(Arch);
314   if (Version < MinVersion || Version > MaxVersion) {
315     ArchsWithBadVersion[(int)Arch] = true;
316     D.Diag(diag::err_drv_cuda_version_unsupported)
317         << CudaArchToString(Arch) << CudaVersionToString(MinVersion)
318         << CudaVersionToString(MaxVersion) << InstallPath
319         << CudaVersionToString(Version);
320   }
321 }
322 
323 void CudaInstallationDetector::print(raw_ostream &OS) const {
324   if (isValid())
325     OS << "Found CUDA installation: " << InstallPath << ", version "
326        << CudaVersionToString(Version) << "\n";
327 }
328 
329 namespace {
330 /// Debug info level for the NVPTX devices. We may need to emit different debug
331 /// info level for the host and for the device itselfi. This type controls
332 /// emission of the debug info for the devices. It either prohibits disable info
333 /// emission completely, or emits debug directives only, or emits same debug
334 /// info as for the host.
335 enum DeviceDebugInfoLevel {
336   DisableDebugInfo,        /// Do not emit debug info for the devices.
337   DebugDirectivesOnly,     /// Emit only debug directives.
338   EmitSameDebugInfoAsHost, /// Use the same debug info level just like for the
339                            /// host.
340 };
341 } // anonymous namespace
342 
343 /// Define debug info level for the NVPTX devices. If the debug info for both
344 /// the host and device are disabled (-g0/-ggdb0 or no debug options at all). If
345 /// only debug directives are requested for the both host and device
346 /// (-gline-directvies-only), or the debug info only for the device is disabled
347 /// (optimization is on and --cuda-noopt-device-debug was not specified), the
348 /// debug directves only must be emitted for the device. Otherwise, use the same
349 /// debug info level just like for the host (with the limitations of only
350 /// supported DWARF2 standard).
351 static DeviceDebugInfoLevel mustEmitDebugInfo(const ArgList &Args) {
352   const Arg *A = Args.getLastArg(options::OPT_O_Group);
353   bool IsDebugEnabled = !A || A->getOption().matches(options::OPT_O0) ||
354                         Args.hasFlag(options::OPT_cuda_noopt_device_debug,
355                                      options::OPT_no_cuda_noopt_device_debug,
356                                      /*Default=*/false);
357   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
358     const Option &Opt = A->getOption();
359     if (Opt.matches(options::OPT_gN_Group)) {
360       if (Opt.matches(options::OPT_g0) || Opt.matches(options::OPT_ggdb0))
361         return DisableDebugInfo;
362       if (Opt.matches(options::OPT_gline_directives_only))
363         return DebugDirectivesOnly;
364     }
365     return IsDebugEnabled ? EmitSameDebugInfoAsHost : DebugDirectivesOnly;
366   }
367   return willEmitRemarks(Args) ? DebugDirectivesOnly : DisableDebugInfo;
368 }
369 
370 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
371                                     const InputInfo &Output,
372                                     const InputInfoList &Inputs,
373                                     const ArgList &Args,
374                                     const char *LinkingOutput) const {
375   const auto &TC =
376       static_cast<const toolchains::NVPTXToolChain &>(getToolChain());
377   assert(TC.getTriple().isNVPTX() && "Wrong platform");
378 
379   StringRef GPUArchName;
380   // If this is a CUDA action we need to extract the device architecture
381   // from the Job's associated architecture, otherwise use the -march=arch
382   // option. This option may come from -Xopenmp-target flag or the default
383   // value.
384   if (JA.isDeviceOffloading(Action::OFK_Cuda)) {
385     GPUArchName = JA.getOffloadingArch();
386   } else {
387     GPUArchName = Args.getLastArgValue(options::OPT_march_EQ);
388     assert(!GPUArchName.empty() && "Must have an architecture passed in.");
389   }
390 
391   // Obtain architecture from the action.
392   CudaArch gpu_arch = StringToCudaArch(GPUArchName);
393   assert(gpu_arch != CudaArch::UNKNOWN &&
394          "Device action expected to have an architecture.");
395 
396   // Check that our installation's ptxas supports gpu_arch.
397   if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
398     TC.CudaInstallation.CheckCudaVersionSupportsArch(gpu_arch);
399   }
400 
401   ArgStringList CmdArgs;
402   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
403   DeviceDebugInfoLevel DIKind = mustEmitDebugInfo(Args);
404   if (DIKind == EmitSameDebugInfoAsHost) {
405     // ptxas does not accept -g option if optimization is enabled, so
406     // we ignore the compiler's -O* options if we want debug info.
407     CmdArgs.push_back("-g");
408     CmdArgs.push_back("--dont-merge-basicblocks");
409     CmdArgs.push_back("--return-at-end");
410   } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
411     // Map the -O we received to -O{0,1,2,3}.
412     //
413     // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
414     // default, so it may correspond more closely to the spirit of clang -O2.
415 
416     // -O3 seems like the least-bad option when -Osomething is specified to
417     // clang but it isn't handled below.
418     StringRef OOpt = "3";
419     if (A->getOption().matches(options::OPT_O4) ||
420         A->getOption().matches(options::OPT_Ofast))
421       OOpt = "3";
422     else if (A->getOption().matches(options::OPT_O0))
423       OOpt = "0";
424     else if (A->getOption().matches(options::OPT_O)) {
425       // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
426       OOpt = llvm::StringSwitch<const char *>(A->getValue())
427                  .Case("1", "1")
428                  .Case("2", "2")
429                  .Case("3", "3")
430                  .Case("s", "2")
431                  .Case("z", "2")
432                  .Default("2");
433     }
434     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
435   } else {
436     // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
437     // to no optimizations, but ptxas's default is -O3.
438     CmdArgs.push_back("-O0");
439   }
440   if (DIKind == DebugDirectivesOnly)
441     CmdArgs.push_back("-lineinfo");
442 
443   // Pass -v to ptxas if it was passed to the driver.
444   if (Args.hasArg(options::OPT_v))
445     CmdArgs.push_back("-v");
446 
447   CmdArgs.push_back("--gpu-name");
448   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
449   CmdArgs.push_back("--output-file");
450   std::string OutputFileName = TC.getInputFilename(Output);
451 
452   // If we are invoking `nvlink` internally we need to output a `.cubin` file.
453   // FIXME: This should hopefully be removed if NVIDIA updates their tooling.
454   if (!C.getInputArgs().getLastArg(options::OPT_c)) {
455     SmallString<256> Filename(Output.getFilename());
456     llvm::sys::path::replace_extension(Filename, "cubin");
457     OutputFileName = Filename.str();
458   }
459   if (Output.isFilename() && OutputFileName != Output.getFilename())
460     C.addTempFile(Args.MakeArgString(OutputFileName));
461 
462   CmdArgs.push_back(Args.MakeArgString(OutputFileName));
463   for (const auto &II : Inputs)
464     CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
465 
466   for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
467     CmdArgs.push_back(Args.MakeArgString(A));
468 
469   bool Relocatable;
470   if (JA.isOffloading(Action::OFK_OpenMP))
471     // In OpenMP we need to generate relocatable code.
472     Relocatable = Args.hasFlag(options::OPT_fopenmp_relocatable_target,
473                                options::OPT_fnoopenmp_relocatable_target,
474                                /*Default=*/true);
475   else if (JA.isOffloading(Action::OFK_Cuda))
476     // In CUDA we generate relocatable code by default.
477     Relocatable = Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
478                                /*Default=*/false);
479   else
480     // Otherwise, we are compiling directly and should create linkable output.
481     Relocatable = true;
482 
483   if (Relocatable)
484     CmdArgs.push_back("-c");
485 
486   const char *Exec;
487   if (Arg *A = Args.getLastArg(options::OPT_ptxas_path_EQ))
488     Exec = A->getValue();
489   else
490     Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
491   C.addCommand(std::make_unique<Command>(
492       JA, *this,
493       ResponseFileSupport{ResponseFileSupport::RF_Full, llvm::sys::WEM_UTF8,
494                           "--options-file"},
495       Exec, CmdArgs, Inputs, Output));
496 }
497 
498 static bool shouldIncludePTX(const ArgList &Args, const char *gpu_arch) {
499   bool includePTX = true;
500   for (Arg *A : Args) {
501     if (!(A->getOption().matches(options::OPT_cuda_include_ptx_EQ) ||
502           A->getOption().matches(options::OPT_no_cuda_include_ptx_EQ)))
503       continue;
504     A->claim();
505     const StringRef ArchStr = A->getValue();
506     if (ArchStr == "all" || ArchStr == gpu_arch) {
507       includePTX = A->getOption().matches(options::OPT_cuda_include_ptx_EQ);
508       continue;
509     }
510   }
511   return includePTX;
512 }
513 
514 // All inputs to this linker must be from CudaDeviceActions, as we need to look
515 // at the Inputs' Actions in order to figure out which GPU architecture they
516 // correspond to.
517 void NVPTX::FatBinary::ConstructJob(Compilation &C, const JobAction &JA,
518                                     const InputInfo &Output,
519                                     const InputInfoList &Inputs,
520                                     const ArgList &Args,
521                                     const char *LinkingOutput) const {
522   const auto &TC =
523       static_cast<const toolchains::CudaToolChain &>(getToolChain());
524   assert(TC.getTriple().isNVPTX() && "Wrong platform");
525 
526   ArgStringList CmdArgs;
527   if (TC.CudaInstallation.version() <= CudaVersion::CUDA_100)
528     CmdArgs.push_back("--cuda");
529   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
530   CmdArgs.push_back(Args.MakeArgString("--create"));
531   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
532   if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
533     CmdArgs.push_back("-g");
534 
535   for (const auto &II : Inputs) {
536     auto *A = II.getAction();
537     assert(A->getInputs().size() == 1 &&
538            "Device offload action is expected to have a single input");
539     const char *gpu_arch_str = A->getOffloadingArch();
540     assert(gpu_arch_str &&
541            "Device action expected to have associated a GPU architecture!");
542     CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
543 
544     if (II.getType() == types::TY_PP_Asm &&
545         !shouldIncludePTX(Args, gpu_arch_str))
546       continue;
547     // We need to pass an Arch of the form "sm_XX" for cubin files and
548     // "compute_XX" for ptx.
549     const char *Arch = (II.getType() == types::TY_PP_Asm)
550                            ? CudaArchToVirtualArchString(gpu_arch)
551                            : gpu_arch_str;
552     CmdArgs.push_back(
553         Args.MakeArgString(llvm::Twine("--image=profile=") + Arch +
554                            ",file=" + getToolChain().getInputFilename(II)));
555   }
556 
557   for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
558     CmdArgs.push_back(Args.MakeArgString(A));
559 
560   const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
561   C.addCommand(std::make_unique<Command>(
562       JA, *this,
563       ResponseFileSupport{ResponseFileSupport::RF_Full, llvm::sys::WEM_UTF8,
564                           "--options-file"},
565       Exec, CmdArgs, Inputs, Output));
566 }
567 
568 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
569                                  const InputInfo &Output,
570                                  const InputInfoList &Inputs,
571                                  const ArgList &Args,
572                                  const char *LinkingOutput) const {
573   const auto &TC =
574       static_cast<const toolchains::NVPTXToolChain &>(getToolChain());
575   assert(TC.getTriple().isNVPTX() && "Wrong platform");
576 
577   ArgStringList CmdArgs;
578   if (Output.isFilename()) {
579     CmdArgs.push_back("-o");
580     CmdArgs.push_back(Output.getFilename());
581   } else {
582     assert(Output.isNothing() && "Invalid output.");
583   }
584 
585   if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
586     CmdArgs.push_back("-g");
587 
588   if (Args.hasArg(options::OPT_v))
589     CmdArgs.push_back("-v");
590 
591   StringRef GPUArch = Args.getLastArgValue(options::OPT_march_EQ);
592   assert(!GPUArch.empty() && "At least one GPU Arch required for nvlink.");
593 
594   CmdArgs.push_back("-arch");
595   CmdArgs.push_back(Args.MakeArgString(GPUArch));
596 
597   // Add paths specified in LIBRARY_PATH environment variable as -L options.
598   addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
599 
600   // Add paths for the default clang library path.
601   SmallString<256> DefaultLibPath =
602       llvm::sys::path::parent_path(TC.getDriver().Dir);
603   llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
604   CmdArgs.push_back(Args.MakeArgString(Twine("-L") + DefaultLibPath));
605 
606   for (const auto &II : Inputs) {
607     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
608         II.getType() == types::TY_LTO_BC || II.getType() == types::TY_LLVM_BC) {
609       C.getDriver().Diag(diag::err_drv_no_linker_llvm_support)
610           << getToolChain().getTripleString();
611       continue;
612     }
613 
614     // Currently, we only pass the input files to the linker, we do not pass
615     // any libraries that may be valid only for the host.
616     if (!II.isFilename())
617       continue;
618 
619     // The 'nvlink' application performs RDC-mode linking when given a '.o'
620     // file and device linking when given a '.cubin' file. We always want to
621     // perform device linking, so just rename any '.o' files.
622     // FIXME: This should hopefully be removed if NVIDIA updates their tooling.
623     auto InputFile = getToolChain().getInputFilename(II);
624     if (llvm::sys::path::extension(InputFile) != ".cubin") {
625       // If there are no actions above this one then this is direct input and we
626       // can copy it. Otherwise the input is internal so a `.cubin` file should
627       // exist.
628       if (II.getAction() && II.getAction()->getInputs().size() == 0) {
629         const char *CubinF =
630             Args.MakeArgString(getToolChain().getDriver().GetTemporaryPath(
631                 llvm::sys::path::stem(InputFile), "cubin"));
632         if (std::error_code EC =
633                 llvm::sys::fs::copy_file(InputFile, C.addTempFile(CubinF)))
634           continue;
635 
636         CmdArgs.push_back(CubinF);
637       } else {
638         SmallString<256> Filename(InputFile);
639         llvm::sys::path::replace_extension(Filename, "cubin");
640         CmdArgs.push_back(Args.MakeArgString(Filename));
641       }
642     } else {
643       CmdArgs.push_back(Args.MakeArgString(InputFile));
644     }
645   }
646 
647   C.addCommand(std::make_unique<Command>(
648       JA, *this,
649       ResponseFileSupport{ResponseFileSupport::RF_Full, llvm::sys::WEM_UTF8,
650                           "--options-file"},
651       Args.MakeArgString(getToolChain().GetProgramPath("nvlink")), CmdArgs,
652       Inputs, Output));
653 }
654 
655 void NVPTX::getNVPTXTargetFeatures(const Driver &D, const llvm::Triple &Triple,
656                                    const llvm::opt::ArgList &Args,
657                                    std::vector<StringRef> &Features) {
658   if (Args.hasArg(options::OPT_cuda_feature_EQ)) {
659     StringRef PtxFeature =
660         Args.getLastArgValue(options::OPT_cuda_feature_EQ, "+ptx42");
661     Features.push_back(Args.MakeArgString(PtxFeature));
662     return;
663   }
664   CudaInstallationDetector CudaInstallation(D, Triple, Args);
665 
666   // New CUDA versions often introduce new instructions that are only supported
667   // by new PTX version, so we need to raise PTX level to enable them in NVPTX
668   // back-end.
669   const char *PtxFeature = nullptr;
670   switch (CudaInstallation.version()) {
671 #define CASE_CUDA_VERSION(CUDA_VER, PTX_VER)                                   \
672   case CudaVersion::CUDA_##CUDA_VER:                                           \
673     PtxFeature = "+ptx" #PTX_VER;                                              \
674     break;
675     CASE_CUDA_VERSION(121, 81);
676     CASE_CUDA_VERSION(120, 80);
677     CASE_CUDA_VERSION(118, 78);
678     CASE_CUDA_VERSION(117, 77);
679     CASE_CUDA_VERSION(116, 76);
680     CASE_CUDA_VERSION(115, 75);
681     CASE_CUDA_VERSION(114, 74);
682     CASE_CUDA_VERSION(113, 73);
683     CASE_CUDA_VERSION(112, 72);
684     CASE_CUDA_VERSION(111, 71);
685     CASE_CUDA_VERSION(110, 70);
686     CASE_CUDA_VERSION(102, 65);
687     CASE_CUDA_VERSION(101, 64);
688     CASE_CUDA_VERSION(100, 63);
689     CASE_CUDA_VERSION(92, 61);
690     CASE_CUDA_VERSION(91, 61);
691     CASE_CUDA_VERSION(90, 60);
692 #undef CASE_CUDA_VERSION
693   default:
694     PtxFeature = "+ptx42";
695   }
696   Features.push_back(PtxFeature);
697 }
698 
699 /// NVPTX toolchain. Our assembler is ptxas, and our linker is nvlink. This
700 /// operates as a stand-alone version of the NVPTX tools without the host
701 /// toolchain.
702 NVPTXToolChain::NVPTXToolChain(const Driver &D, const llvm::Triple &Triple,
703                                const llvm::Triple &HostTriple,
704                                const ArgList &Args, bool Freestanding = false)
705     : ToolChain(D, Triple, Args), CudaInstallation(D, HostTriple, Args),
706       Freestanding(Freestanding) {
707   if (CudaInstallation.isValid())
708     getProgramPaths().push_back(std::string(CudaInstallation.getBinPath()));
709   // Lookup binaries into the driver directory, this is used to
710   // discover the 'nvptx-arch' executable.
711   getProgramPaths().push_back(getDriver().Dir);
712 }
713 
714 /// We only need the host triple to locate the CUDA binary utilities, use the
715 /// system's default triple if not provided.
716 NVPTXToolChain::NVPTXToolChain(const Driver &D, const llvm::Triple &Triple,
717                                const ArgList &Args)
718     : NVPTXToolChain(D, Triple, llvm::Triple(LLVM_HOST_TRIPLE), Args,
719                      /*Freestanding=*/true) {}
720 
721 llvm::opt::DerivedArgList *
722 NVPTXToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
723                               StringRef BoundArch,
724                               Action::OffloadKind DeviceOffloadKind) const {
725   DerivedArgList *DAL =
726       ToolChain::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
727   if (!DAL)
728     DAL = new DerivedArgList(Args.getBaseArgs());
729 
730   const OptTable &Opts = getDriver().getOpts();
731 
732   for (Arg *A : Args)
733     if (!llvm::is_contained(*DAL, A))
734       DAL->append(A);
735 
736   if (!DAL->hasArg(options::OPT_march_EQ))
737     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ),
738                       CudaArchToString(CudaArch::CudaDefault));
739 
740   return DAL;
741 }
742 
743 void NVPTXToolChain::addClangTargetOptions(
744     const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
745     Action::OffloadKind DeviceOffloadingKind) const {
746   // If we are compiling with a standalone NVPTX toolchain we want to try to
747   // mimic a standard environment as much as possible. So we enable lowering
748   // ctor / dtor functions to global symbols that can be registered.
749   if (Freestanding)
750     CC1Args.append({"-mllvm", "--nvptx-lower-global-ctor-dtor"});
751 }
752 
753 bool NVPTXToolChain::supportsDebugInfoOption(const llvm::opt::Arg *A) const {
754   const Option &O = A->getOption();
755   return (O.matches(options::OPT_gN_Group) &&
756           !O.matches(options::OPT_gmodules)) ||
757          O.matches(options::OPT_g_Flag) ||
758          O.matches(options::OPT_ggdbN_Group) || O.matches(options::OPT_ggdb) ||
759          O.matches(options::OPT_gdwarf) || O.matches(options::OPT_gdwarf_2) ||
760          O.matches(options::OPT_gdwarf_3) || O.matches(options::OPT_gdwarf_4) ||
761          O.matches(options::OPT_gdwarf_5) ||
762          O.matches(options::OPT_gcolumn_info);
763 }
764 
765 void NVPTXToolChain::adjustDebugInfoKind(
766     llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
767     const ArgList &Args) const {
768   switch (mustEmitDebugInfo(Args)) {
769   case DisableDebugInfo:
770     DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
771     break;
772   case DebugDirectivesOnly:
773     DebugInfoKind = llvm::codegenoptions::DebugDirectivesOnly;
774     break;
775   case EmitSameDebugInfoAsHost:
776     // Use same debug info level as the host.
777     break;
778   }
779 }
780 
781 /// CUDA toolchain.  Our assembler is ptxas, and our "linker" is fatbinary,
782 /// which isn't properly a linker but nonetheless performs the step of stitching
783 /// together object files from the assembler into a single blob.
784 
785 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
786                              const ToolChain &HostTC, const ArgList &Args)
787     : NVPTXToolChain(D, Triple, HostTC.getTriple(), Args), HostTC(HostTC) {}
788 
789 void CudaToolChain::addClangTargetOptions(
790     const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
791     Action::OffloadKind DeviceOffloadingKind) const {
792   HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
793 
794   StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
795   assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
796   assert((DeviceOffloadingKind == Action::OFK_OpenMP ||
797           DeviceOffloadingKind == Action::OFK_Cuda) &&
798          "Only OpenMP or CUDA offloading kinds are supported for NVIDIA GPUs.");
799 
800   if (DeviceOffloadingKind == Action::OFK_Cuda) {
801     CC1Args.append(
802         {"-fcuda-is-device", "-mllvm", "-enable-memcpyopt-without-libcalls"});
803 
804     if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
805                            options::OPT_fno_cuda_approx_transcendentals, false))
806       CC1Args.push_back("-fcuda-approx-transcendentals");
807 
808     // Unsized function arguments used for variadics were introduced in CUDA-9.0
809     // We still do not support generating code that actually uses variadic
810     // arguments yet, but we do need to allow parsing them as recent CUDA
811     // headers rely on that. https://github.com/llvm/llvm-project/issues/58410
812     if (CudaInstallation.version() >= CudaVersion::CUDA_90)
813       CC1Args.push_back("-fcuda-allow-variadic-functions");
814   }
815 
816   if (DriverArgs.hasArg(options::OPT_nogpulib))
817     return;
818 
819   if (DeviceOffloadingKind == Action::OFK_OpenMP &&
820       DriverArgs.hasArg(options::OPT_S))
821     return;
822 
823   std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(GpuArch);
824   if (LibDeviceFile.empty()) {
825     getDriver().Diag(diag::err_drv_no_cuda_libdevice) << GpuArch;
826     return;
827   }
828 
829   CC1Args.push_back("-mlink-builtin-bitcode");
830   CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
831 
832   clang::CudaVersion CudaInstallationVersion = CudaInstallation.version();
833 
834   if (DriverArgs.hasFlag(options::OPT_fcuda_short_ptr,
835                          options::OPT_fno_cuda_short_ptr, false))
836     CC1Args.append({"-mllvm", "--nvptx-short-ptr"});
837 
838   if (CudaInstallationVersion >= CudaVersion::UNKNOWN)
839     CC1Args.push_back(
840         DriverArgs.MakeArgString(Twine("-target-sdk-version=") +
841                                  CudaVersionToString(CudaInstallationVersion)));
842 
843   if (DeviceOffloadingKind == Action::OFK_OpenMP) {
844     if (CudaInstallationVersion < CudaVersion::CUDA_92) {
845       getDriver().Diag(
846           diag::err_drv_omp_offload_target_cuda_version_not_support)
847           << CudaVersionToString(CudaInstallationVersion);
848       return;
849     }
850 
851     // Link the bitcode library late if we're using device LTO.
852     if (getDriver().isUsingLTO(/* IsOffload */ true))
853       return;
854 
855     addOpenMPDeviceRTL(getDriver(), DriverArgs, CC1Args, GpuArch.str(),
856                        getTriple());
857   }
858 }
859 
860 llvm::DenormalMode CudaToolChain::getDefaultDenormalModeForType(
861     const llvm::opt::ArgList &DriverArgs, const JobAction &JA,
862     const llvm::fltSemantics *FPType) const {
863   if (JA.getOffloadingDeviceKind() == Action::OFK_Cuda) {
864     if (FPType && FPType == &llvm::APFloat::IEEEsingle() &&
865         DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,
866                            options::OPT_fno_gpu_flush_denormals_to_zero, false))
867       return llvm::DenormalMode::getPreserveSign();
868   }
869 
870   assert(JA.getOffloadingDeviceKind() != Action::OFK_Host);
871   return llvm::DenormalMode::getIEEE();
872 }
873 
874 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
875                                        ArgStringList &CC1Args) const {
876   // Check our CUDA version if we're going to include the CUDA headers.
877   if (!DriverArgs.hasArg(options::OPT_nogpuinc) &&
878       !DriverArgs.hasArg(options::OPT_no_cuda_version_check)) {
879     StringRef Arch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
880     assert(!Arch.empty() && "Must have an explicit GPU arch.");
881     CudaInstallation.CheckCudaVersionSupportsArch(StringToCudaArch(Arch));
882   }
883   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
884 }
885 
886 std::string CudaToolChain::getInputFilename(const InputInfo &Input) const {
887   // Only object files are changed, for example assembly files keep their .s
888   // extensions. If the user requested device-only compilation don't change it.
889   if (Input.getType() != types::TY_Object || getDriver().offloadDeviceOnly())
890     return ToolChain::getInputFilename(Input);
891 
892   // Replace extension for object files with cubin because nvlink relies on
893   // these particular file names.
894   SmallString<256> Filename(ToolChain::getInputFilename(Input));
895   llvm::sys::path::replace_extension(Filename, "cubin");
896   return std::string(Filename.str());
897 }
898 
899 llvm::opt::DerivedArgList *
900 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
901                              StringRef BoundArch,
902                              Action::OffloadKind DeviceOffloadKind) const {
903   DerivedArgList *DAL =
904       HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
905   if (!DAL)
906     DAL = new DerivedArgList(Args.getBaseArgs());
907 
908   const OptTable &Opts = getDriver().getOpts();
909 
910   // For OpenMP device offloading, append derived arguments. Make sure
911   // flags are not duplicated.
912   // Also append the compute capability.
913   if (DeviceOffloadKind == Action::OFK_OpenMP) {
914     for (Arg *A : Args)
915       if (!llvm::is_contained(*DAL, A))
916         DAL->append(A);
917 
918     if (!DAL->hasArg(options::OPT_march_EQ)) {
919       StringRef Arch = BoundArch;
920       if (Arch.empty()) {
921         auto ArchsOrErr = getSystemGPUArchs(Args);
922         if (!ArchsOrErr) {
923           std::string ErrMsg =
924               llvm::formatv("{0}", llvm::fmt_consume(ArchsOrErr.takeError()));
925           getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
926               << llvm::Triple::getArchTypeName(getArch()) << ErrMsg << "-march";
927           Arch = CudaArchToString(CudaArch::CudaDefault);
928         } else {
929           Arch = Args.MakeArgString(ArchsOrErr->front());
930         }
931       }
932       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), Arch);
933     }
934 
935     return DAL;
936   }
937 
938   for (Arg *A : Args) {
939     DAL->append(A);
940   }
941 
942   if (!BoundArch.empty()) {
943     DAL->eraseArg(options::OPT_march_EQ);
944     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ),
945                       BoundArch);
946   }
947   return DAL;
948 }
949 
950 Expected<SmallVector<std::string>>
951 CudaToolChain::getSystemGPUArchs(const ArgList &Args) const {
952   // Detect NVIDIA GPUs availible on the system.
953   std::string Program;
954   if (Arg *A = Args.getLastArg(options::OPT_nvptx_arch_tool_EQ))
955     Program = A->getValue();
956   else
957     Program = GetProgramPath("nvptx-arch");
958 
959   auto StdoutOrErr = executeToolChainProgram(Program);
960   if (!StdoutOrErr)
961     return StdoutOrErr.takeError();
962 
963   SmallVector<std::string, 1> GPUArchs;
964   for (StringRef Arch : llvm::split((*StdoutOrErr)->getBuffer(), "\n"))
965     if (!Arch.empty())
966       GPUArchs.push_back(Arch.str());
967 
968   if (GPUArchs.empty())
969     return llvm::createStringError(std::error_code(),
970                                    "No NVIDIA GPU detected in the system");
971 
972   return std::move(GPUArchs);
973 }
974 
975 Tool *NVPTXToolChain::buildAssembler() const {
976   return new tools::NVPTX::Assembler(*this);
977 }
978 
979 Tool *NVPTXToolChain::buildLinker() const {
980   return new tools::NVPTX::Linker(*this);
981 }
982 
983 Tool *CudaToolChain::buildAssembler() const {
984   return new tools::NVPTX::Assembler(*this);
985 }
986 
987 Tool *CudaToolChain::buildLinker() const {
988   return new tools::NVPTX::FatBinary(*this);
989 }
990 
991 void CudaToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
992   HostTC.addClangWarningOptions(CC1Args);
993 }
994 
995 ToolChain::CXXStdlibType
996 CudaToolChain::GetCXXStdlibType(const ArgList &Args) const {
997   return HostTC.GetCXXStdlibType(Args);
998 }
999 
1000 void CudaToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1001                                               ArgStringList &CC1Args) const {
1002   HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
1003 
1004   if (!DriverArgs.hasArg(options::OPT_nogpuinc) && CudaInstallation.isValid())
1005     CC1Args.append(
1006         {"-internal-isystem",
1007          DriverArgs.MakeArgString(CudaInstallation.getIncludePath())});
1008 }
1009 
1010 void CudaToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
1011                                                  ArgStringList &CC1Args) const {
1012   HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
1013 }
1014 
1015 void CudaToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
1016                                         ArgStringList &CC1Args) const {
1017   HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
1018 }
1019 
1020 SanitizerMask CudaToolChain::getSupportedSanitizers() const {
1021   // The CudaToolChain only supports sanitizers in the sense that it allows
1022   // sanitizer arguments on the command line if they are supported by the host
1023   // toolchain. The CudaToolChain will actually ignore any command line
1024   // arguments for any of these "supported" sanitizers. That means that no
1025   // sanitization of device code is actually supported at this time.
1026   //
1027   // This behavior is necessary because the host and device toolchains
1028   // invocations often share the command line, so the device toolchain must
1029   // tolerate flags meant only for the host toolchain.
1030   return HostTC.getSupportedSanitizers();
1031 }
1032 
1033 VersionTuple CudaToolChain::computeMSVCVersion(const Driver *D,
1034                                                const ArgList &Args) const {
1035   return HostTC.computeMSVCVersion(D, Args);
1036 }
1037