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