xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/AMDGPU.cpp (revision 2e3507c25e42292b45a5482e116d278f5515d04d)
1 //===--- AMDGPU.cpp - AMDGPU 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 "AMDGPU.h"
10 #include "CommonArgs.h"
11 #include "clang/Basic/TargetID.h"
12 #include "clang/Config/config.h"
13 #include "clang/Driver/Compilation.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/InputInfo.h"
16 #include "clang/Driver/Options.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Option/ArgList.h"
19 #include "llvm/Support/Error.h"
20 #include "llvm/Support/LineIterator.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/Process.h"
23 #include "llvm/Support/VirtualFileSystem.h"
24 #include "llvm/TargetParser/Host.h"
25 #include <optional>
26 #include <system_error>
27 
28 using namespace clang::driver;
29 using namespace clang::driver::tools;
30 using namespace clang::driver::toolchains;
31 using namespace clang;
32 using namespace llvm::opt;
33 
34 // Look for sub-directory starts with PackageName under ROCm candidate path.
35 // If there is one and only one matching sub-directory found, append the
36 // sub-directory to Path. If there is no matching sub-directory or there are
37 // more than one matching sub-directories, diagnose them. Returns the full
38 // path of the package if there is only one matching sub-directory, otherwise
39 // returns an empty string.
40 llvm::SmallString<0>
41 RocmInstallationDetector::findSPACKPackage(const Candidate &Cand,
42                                            StringRef PackageName) {
43   if (!Cand.isSPACK())
44     return {};
45   std::error_code EC;
46   std::string Prefix = Twine(PackageName + "-" + Cand.SPACKReleaseStr).str();
47   llvm::SmallVector<llvm::SmallString<0>> SubDirs;
48   for (llvm::vfs::directory_iterator File = D.getVFS().dir_begin(Cand.Path, EC),
49                                      FileEnd;
50        File != FileEnd && !EC; File.increment(EC)) {
51     llvm::StringRef FileName = llvm::sys::path::filename(File->path());
52     if (FileName.startswith(Prefix)) {
53       SubDirs.push_back(FileName);
54       if (SubDirs.size() > 1)
55         break;
56     }
57   }
58   if (SubDirs.size() == 1) {
59     auto PackagePath = Cand.Path;
60     llvm::sys::path::append(PackagePath, SubDirs[0]);
61     return PackagePath;
62   }
63   if (SubDirs.size() == 0 && Verbose) {
64     llvm::errs() << "SPACK package " << Prefix << " not found at " << Cand.Path
65                  << '\n';
66     return {};
67   }
68 
69   if (SubDirs.size() > 1 && Verbose) {
70     llvm::errs() << "Cannot use SPACK package " << Prefix << " at " << Cand.Path
71                  << " due to multiple installations for the same version\n";
72   }
73   return {};
74 }
75 
76 void RocmInstallationDetector::scanLibDevicePath(llvm::StringRef Path) {
77   assert(!Path.empty());
78 
79   const StringRef Suffix(".bc");
80   const StringRef Suffix2(".amdgcn.bc");
81 
82   std::error_code EC;
83   for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(Path, EC), LE;
84        !EC && LI != LE; LI = LI.increment(EC)) {
85     StringRef FilePath = LI->path();
86     StringRef FileName = llvm::sys::path::filename(FilePath);
87     if (!FileName.endswith(Suffix))
88       continue;
89 
90     StringRef BaseName;
91     if (FileName.endswith(Suffix2))
92       BaseName = FileName.drop_back(Suffix2.size());
93     else if (FileName.endswith(Suffix))
94       BaseName = FileName.drop_back(Suffix.size());
95 
96     const StringRef ABIVersionPrefix = "oclc_abi_version_";
97     if (BaseName == "ocml") {
98       OCML = FilePath;
99     } else if (BaseName == "ockl") {
100       OCKL = FilePath;
101     } else if (BaseName == "opencl") {
102       OpenCL = FilePath;
103     } else if (BaseName == "hip") {
104       HIP = FilePath;
105     } else if (BaseName == "asanrtl") {
106       AsanRTL = FilePath;
107     } else if (BaseName == "oclc_finite_only_off") {
108       FiniteOnly.Off = FilePath;
109     } else if (BaseName == "oclc_finite_only_on") {
110       FiniteOnly.On = FilePath;
111     } else if (BaseName == "oclc_daz_opt_on") {
112       DenormalsAreZero.On = FilePath;
113     } else if (BaseName == "oclc_daz_opt_off") {
114       DenormalsAreZero.Off = FilePath;
115     } else if (BaseName == "oclc_correctly_rounded_sqrt_on") {
116       CorrectlyRoundedSqrt.On = FilePath;
117     } else if (BaseName == "oclc_correctly_rounded_sqrt_off") {
118       CorrectlyRoundedSqrt.Off = FilePath;
119     } else if (BaseName == "oclc_unsafe_math_on") {
120       UnsafeMath.On = FilePath;
121     } else if (BaseName == "oclc_unsafe_math_off") {
122       UnsafeMath.Off = FilePath;
123     } else if (BaseName == "oclc_wavefrontsize64_on") {
124       WavefrontSize64.On = FilePath;
125     } else if (BaseName == "oclc_wavefrontsize64_off") {
126       WavefrontSize64.Off = FilePath;
127     } else if (BaseName.startswith(ABIVersionPrefix)) {
128       unsigned ABIVersionNumber;
129       if (BaseName.drop_front(ABIVersionPrefix.size())
130               .getAsInteger(/*Redex=*/0, ABIVersionNumber))
131         continue;
132       ABIVersionMap[ABIVersionNumber] = FilePath.str();
133     } else {
134       // Process all bitcode filenames that look like
135       // ocl_isa_version_XXX.amdgcn.bc
136       const StringRef DeviceLibPrefix = "oclc_isa_version_";
137       if (!BaseName.startswith(DeviceLibPrefix))
138         continue;
139 
140       StringRef IsaVersionNumber =
141         BaseName.drop_front(DeviceLibPrefix.size());
142 
143       llvm::Twine GfxName = Twine("gfx") + IsaVersionNumber;
144       SmallString<8> Tmp;
145       LibDeviceMap.insert(
146         std::make_pair(GfxName.toStringRef(Tmp), FilePath.str()));
147     }
148   }
149 }
150 
151 // Parse and extract version numbers from `.hipVersion`. Return `true` if
152 // the parsing fails.
153 bool RocmInstallationDetector::parseHIPVersionFile(llvm::StringRef V) {
154   SmallVector<StringRef, 4> VersionParts;
155   V.split(VersionParts, '\n');
156   unsigned Major = ~0U;
157   unsigned Minor = ~0U;
158   for (auto Part : VersionParts) {
159     auto Splits = Part.rtrim().split('=');
160     if (Splits.first == "HIP_VERSION_MAJOR") {
161       if (Splits.second.getAsInteger(0, Major))
162         return true;
163     } else if (Splits.first == "HIP_VERSION_MINOR") {
164       if (Splits.second.getAsInteger(0, Minor))
165         return true;
166     } else if (Splits.first == "HIP_VERSION_PATCH")
167       VersionPatch = Splits.second.str();
168   }
169   if (Major == ~0U || Minor == ~0U)
170     return true;
171   VersionMajorMinor = llvm::VersionTuple(Major, Minor);
172   DetectedVersion =
173       (Twine(Major) + "." + Twine(Minor) + "." + VersionPatch).str();
174   return false;
175 }
176 
177 /// \returns a list of candidate directories for ROCm installation, which is
178 /// cached and populated only once.
179 const SmallVectorImpl<RocmInstallationDetector::Candidate> &
180 RocmInstallationDetector::getInstallationPathCandidates() {
181 
182   // Return the cached candidate list if it has already been populated.
183   if (!ROCmSearchDirs.empty())
184     return ROCmSearchDirs;
185 
186   auto DoPrintROCmSearchDirs = [&]() {
187     if (PrintROCmSearchDirs)
188       for (auto Cand : ROCmSearchDirs) {
189         llvm::errs() << "ROCm installation search path";
190         if (Cand.isSPACK())
191           llvm::errs() << " (Spack " << Cand.SPACKReleaseStr << ")";
192         llvm::errs() << ": " << Cand.Path << '\n';
193       }
194   };
195 
196   // For candidate specified by --rocm-path we do not do strict check, i.e.,
197   // checking existence of HIP version file and device library files.
198   if (!RocmPathArg.empty()) {
199     ROCmSearchDirs.emplace_back(RocmPathArg.str());
200     DoPrintROCmSearchDirs();
201     return ROCmSearchDirs;
202   } else if (std::optional<std::string> RocmPathEnv =
203                  llvm::sys::Process::GetEnv("ROCM_PATH")) {
204     if (!RocmPathEnv->empty()) {
205       ROCmSearchDirs.emplace_back(std::move(*RocmPathEnv));
206       DoPrintROCmSearchDirs();
207       return ROCmSearchDirs;
208     }
209   }
210 
211   // Try to find relative to the compiler binary.
212   const char *InstallDir = D.getInstalledDir();
213 
214   // Check both a normal Unix prefix position of the clang binary, as well as
215   // the Windows-esque layout the ROCm packages use with the host architecture
216   // subdirectory of bin.
217   auto DeduceROCmPath = [](StringRef ClangPath) {
218     // Strip off directory (usually bin)
219     StringRef ParentDir = llvm::sys::path::parent_path(ClangPath);
220     StringRef ParentName = llvm::sys::path::filename(ParentDir);
221 
222     // Some builds use bin/{host arch}, so go up again.
223     if (ParentName == "bin") {
224       ParentDir = llvm::sys::path::parent_path(ParentDir);
225       ParentName = llvm::sys::path::filename(ParentDir);
226     }
227 
228     // Detect ROCm packages built with SPACK.
229     // clang is installed at
230     // <rocm_root>/llvm-amdgpu-<rocm_release_string>-<hash>/bin directory.
231     // We only consider the parent directory of llvm-amdgpu package as ROCm
232     // installation candidate for SPACK.
233     if (ParentName.startswith("llvm-amdgpu-")) {
234       auto SPACKPostfix =
235           ParentName.drop_front(strlen("llvm-amdgpu-")).split('-');
236       auto SPACKReleaseStr = SPACKPostfix.first;
237       if (!SPACKReleaseStr.empty()) {
238         ParentDir = llvm::sys::path::parent_path(ParentDir);
239         return Candidate(ParentDir.str(), /*StrictChecking=*/true,
240                          SPACKReleaseStr);
241       }
242     }
243 
244     // Some versions of the rocm llvm package install to /opt/rocm/llvm/bin
245     // Some versions of the aomp package install to /opt/rocm/aomp/bin
246     if (ParentName == "llvm" || ParentName.startswith("aomp"))
247       ParentDir = llvm::sys::path::parent_path(ParentDir);
248 
249     return Candidate(ParentDir.str(), /*StrictChecking=*/true);
250   };
251 
252   // Deduce ROCm path by the path used to invoke clang. Do not resolve symbolic
253   // link of clang itself.
254   ROCmSearchDirs.emplace_back(DeduceROCmPath(InstallDir));
255 
256   // Deduce ROCm path by the real path of the invoked clang, resolving symbolic
257   // link of clang itself.
258   llvm::SmallString<256> RealClangPath;
259   llvm::sys::fs::real_path(D.getClangProgramPath(), RealClangPath);
260   auto ParentPath = llvm::sys::path::parent_path(RealClangPath);
261   if (ParentPath != InstallDir)
262     ROCmSearchDirs.emplace_back(DeduceROCmPath(ParentPath));
263 
264   // Device library may be installed in clang or resource directory.
265   auto ClangRoot = llvm::sys::path::parent_path(InstallDir);
266   auto RealClangRoot = llvm::sys::path::parent_path(ParentPath);
267   ROCmSearchDirs.emplace_back(ClangRoot.str(), /*StrictChecking=*/true);
268   if (RealClangRoot != ClangRoot)
269     ROCmSearchDirs.emplace_back(RealClangRoot.str(), /*StrictChecking=*/true);
270   ROCmSearchDirs.emplace_back(D.ResourceDir,
271                               /*StrictChecking=*/true);
272 
273   ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/rocm",
274                               /*StrictChecking=*/true);
275 
276   // Find the latest /opt/rocm-{release} directory.
277   std::error_code EC;
278   std::string LatestROCm;
279   llvm::VersionTuple LatestVer;
280   // Get ROCm version from ROCm directory name.
281   auto GetROCmVersion = [](StringRef DirName) {
282     llvm::VersionTuple V;
283     std::string VerStr = DirName.drop_front(strlen("rocm-")).str();
284     // The ROCm directory name follows the format of
285     // rocm-{major}.{minor}.{subMinor}[-{build}]
286     std::replace(VerStr.begin(), VerStr.end(), '-', '.');
287     V.tryParse(VerStr);
288     return V;
289   };
290   for (llvm::vfs::directory_iterator
291            File = D.getVFS().dir_begin(D.SysRoot + "/opt", EC),
292            FileEnd;
293        File != FileEnd && !EC; File.increment(EC)) {
294     llvm::StringRef FileName = llvm::sys::path::filename(File->path());
295     if (!FileName.startswith("rocm-"))
296       continue;
297     if (LatestROCm.empty()) {
298       LatestROCm = FileName.str();
299       LatestVer = GetROCmVersion(LatestROCm);
300       continue;
301     }
302     auto Ver = GetROCmVersion(FileName);
303     if (LatestVer < Ver) {
304       LatestROCm = FileName.str();
305       LatestVer = Ver;
306     }
307   }
308   if (!LatestROCm.empty())
309     ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/" + LatestROCm,
310                                 /*StrictChecking=*/true);
311 
312   ROCmSearchDirs.emplace_back(D.SysRoot + "/usr/local",
313                               /*StrictChecking=*/true);
314   ROCmSearchDirs.emplace_back(D.SysRoot + "/usr",
315                               /*StrictChecking=*/true);
316 
317   DoPrintROCmSearchDirs();
318   return ROCmSearchDirs;
319 }
320 
321 RocmInstallationDetector::RocmInstallationDetector(
322     const Driver &D, const llvm::Triple &HostTriple,
323     const llvm::opt::ArgList &Args, bool DetectHIPRuntime, bool DetectDeviceLib)
324     : D(D) {
325   Verbose = Args.hasArg(options::OPT_v);
326   RocmPathArg = Args.getLastArgValue(clang::driver::options::OPT_rocm_path_EQ);
327   PrintROCmSearchDirs =
328       Args.hasArg(clang::driver::options::OPT_print_rocm_search_dirs);
329   RocmDeviceLibPathArg =
330       Args.getAllArgValues(clang::driver::options::OPT_rocm_device_lib_path_EQ);
331   HIPPathArg = Args.getLastArgValue(clang::driver::options::OPT_hip_path_EQ);
332   if (auto *A = Args.getLastArg(clang::driver::options::OPT_hip_version_EQ)) {
333     HIPVersionArg = A->getValue();
334     unsigned Major = ~0U;
335     unsigned Minor = ~0U;
336     SmallVector<StringRef, 3> Parts;
337     HIPVersionArg.split(Parts, '.');
338     if (Parts.size())
339       Parts[0].getAsInteger(0, Major);
340     if (Parts.size() > 1)
341       Parts[1].getAsInteger(0, Minor);
342     if (Parts.size() > 2)
343       VersionPatch = Parts[2].str();
344     if (VersionPatch.empty())
345       VersionPatch = "0";
346     if (Major != ~0U && Minor == ~0U)
347       Minor = 0;
348     if (Major == ~0U || Minor == ~0U)
349       D.Diag(diag::err_drv_invalid_value)
350           << A->getAsString(Args) << HIPVersionArg;
351 
352     VersionMajorMinor = llvm::VersionTuple(Major, Minor);
353     DetectedVersion =
354         (Twine(Major) + "." + Twine(Minor) + "." + VersionPatch).str();
355   } else {
356     VersionPatch = DefaultVersionPatch;
357     VersionMajorMinor =
358         llvm::VersionTuple(DefaultVersionMajor, DefaultVersionMinor);
359     DetectedVersion = (Twine(DefaultVersionMajor) + "." +
360                        Twine(DefaultVersionMinor) + "." + VersionPatch)
361                           .str();
362   }
363 
364   if (DetectHIPRuntime)
365     detectHIPRuntime();
366   if (DetectDeviceLib)
367     detectDeviceLibrary();
368 }
369 
370 void RocmInstallationDetector::detectDeviceLibrary() {
371   assert(LibDevicePath.empty());
372 
373   if (!RocmDeviceLibPathArg.empty())
374     LibDevicePath = RocmDeviceLibPathArg[RocmDeviceLibPathArg.size() - 1];
375   else if (std::optional<std::string> LibPathEnv =
376                llvm::sys::Process::GetEnv("HIP_DEVICE_LIB_PATH"))
377     LibDevicePath = std::move(*LibPathEnv);
378 
379   auto &FS = D.getVFS();
380   if (!LibDevicePath.empty()) {
381     // Maintain compatability with HIP flag/envvar pointing directly at the
382     // bitcode library directory. This points directly at the library path instead
383     // of the rocm root installation.
384     if (!FS.exists(LibDevicePath))
385       return;
386 
387     scanLibDevicePath(LibDevicePath);
388     HasDeviceLibrary = allGenericLibsValid() && !LibDeviceMap.empty();
389     return;
390   }
391 
392   // Check device library exists at the given path.
393   auto CheckDeviceLib = [&](StringRef Path, bool StrictChecking) {
394     bool CheckLibDevice = (!NoBuiltinLibs || StrictChecking);
395     if (CheckLibDevice && !FS.exists(Path))
396       return false;
397 
398     scanLibDevicePath(Path);
399 
400     if (!NoBuiltinLibs) {
401       // Check that the required non-target libraries are all available.
402       if (!allGenericLibsValid())
403         return false;
404 
405       // Check that we have found at least one libdevice that we can link in
406       // if -nobuiltinlib hasn't been specified.
407       if (LibDeviceMap.empty())
408         return false;
409     }
410     return true;
411   };
412 
413   // Find device libraries in <LLVM_DIR>/lib/clang/<ver>/lib/amdgcn/bitcode
414   LibDevicePath = D.ResourceDir;
415   llvm::sys::path::append(LibDevicePath, CLANG_INSTALL_LIBDIR_BASENAME,
416                           "amdgcn", "bitcode");
417   HasDeviceLibrary = CheckDeviceLib(LibDevicePath, true);
418   if (HasDeviceLibrary)
419     return;
420 
421   // Find device libraries in a legacy ROCm directory structure
422   // ${ROCM_ROOT}/amdgcn/bitcode/*
423   auto &ROCmDirs = getInstallationPathCandidates();
424   for (const auto &Candidate : ROCmDirs) {
425     LibDevicePath = Candidate.Path;
426     llvm::sys::path::append(LibDevicePath, "amdgcn", "bitcode");
427     HasDeviceLibrary = CheckDeviceLib(LibDevicePath, Candidate.StrictChecking);
428     if (HasDeviceLibrary)
429       return;
430   }
431 }
432 
433 void RocmInstallationDetector::detectHIPRuntime() {
434   SmallVector<Candidate, 4> HIPSearchDirs;
435   if (!HIPPathArg.empty())
436     HIPSearchDirs.emplace_back(HIPPathArg.str());
437   else if (std::optional<std::string> HIPPathEnv =
438                llvm::sys::Process::GetEnv("HIP_PATH")) {
439     if (!HIPPathEnv->empty())
440       HIPSearchDirs.emplace_back(std::move(*HIPPathEnv));
441   }
442   if (HIPSearchDirs.empty())
443     HIPSearchDirs.append(getInstallationPathCandidates());
444   auto &FS = D.getVFS();
445 
446   for (const auto &Candidate : HIPSearchDirs) {
447     InstallPath = Candidate.Path;
448     if (InstallPath.empty() || !FS.exists(InstallPath))
449       continue;
450     // HIP runtime built by SPACK is installed to
451     // <rocm_root>/hip-<rocm_release_string>-<hash> directory.
452     auto SPACKPath = findSPACKPackage(Candidate, "hip");
453     InstallPath = SPACKPath.empty() ? InstallPath : SPACKPath;
454 
455     BinPath = InstallPath;
456     llvm::sys::path::append(BinPath, "bin");
457     IncludePath = InstallPath;
458     llvm::sys::path::append(IncludePath, "include");
459     LibPath = InstallPath;
460     llvm::sys::path::append(LibPath, "lib");
461     SharePath = InstallPath;
462     llvm::sys::path::append(SharePath, "share");
463 
464     // Get parent of InstallPath and append "share"
465     SmallString<0> ParentSharePath = llvm::sys::path::parent_path(InstallPath);
466     llvm::sys::path::append(ParentSharePath, "share");
467 
468     auto Append = [](SmallString<0> &path, const Twine &a, const Twine &b = "",
469                      const Twine &c = "", const Twine &d = "") {
470       SmallString<0> newpath = path;
471       llvm::sys::path::append(newpath, a, b, c, d);
472       return newpath;
473     };
474     // If HIP version file can be found and parsed, use HIP version from there.
475     for (const auto &VersionFilePath :
476          {Append(SharePath, "hip", "version"),
477           Append(ParentSharePath, "hip", "version"),
478           Append(BinPath, ".hipVersion")}) {
479       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
480           FS.getBufferForFile(VersionFilePath);
481       if (!VersionFile)
482         continue;
483       if (HIPVersionArg.empty() && VersionFile)
484         if (parseHIPVersionFile((*VersionFile)->getBuffer()))
485           continue;
486 
487       HasHIPRuntime = true;
488       return;
489     }
490     // Otherwise, if -rocm-path is specified (no strict checking), use the
491     // default HIP version or specified by --hip-version.
492     if (!Candidate.StrictChecking) {
493       HasHIPRuntime = true;
494       return;
495     }
496   }
497   HasHIPRuntime = false;
498 }
499 
500 void RocmInstallationDetector::print(raw_ostream &OS) const {
501   if (hasHIPRuntime())
502     OS << "Found HIP installation: " << InstallPath << ", version "
503        << DetectedVersion << '\n';
504 }
505 
506 void RocmInstallationDetector::AddHIPIncludeArgs(const ArgList &DriverArgs,
507                                                  ArgStringList &CC1Args) const {
508   bool UsesRuntimeWrapper = VersionMajorMinor > llvm::VersionTuple(3, 5) &&
509                             !DriverArgs.hasArg(options::OPT_nohipwrapperinc);
510 
511   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
512     // HIP header includes standard library wrapper headers under clang
513     // cuda_wrappers directory. Since these wrapper headers include_next
514     // standard C++ headers, whereas libc++ headers include_next other clang
515     // headers. The include paths have to follow this order:
516     // - wrapper include path
517     // - standard C++ include path
518     // - other clang include path
519     // Since standard C++ and other clang include paths are added in other
520     // places after this function, here we only need to make sure wrapper
521     // include path is added.
522     //
523     // ROCm 3.5 does not fully support the wrapper headers. Therefore it needs
524     // a workaround.
525     SmallString<128> P(D.ResourceDir);
526     if (UsesRuntimeWrapper)
527       llvm::sys::path::append(P, "include", "cuda_wrappers");
528     CC1Args.push_back("-internal-isystem");
529     CC1Args.push_back(DriverArgs.MakeArgString(P));
530   }
531 
532   if (DriverArgs.hasArg(options::OPT_nogpuinc))
533     return;
534 
535   if (!hasHIPRuntime()) {
536     D.Diag(diag::err_drv_no_hip_runtime);
537     return;
538   }
539 
540   CC1Args.push_back("-idirafter");
541   CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
542   if (UsesRuntimeWrapper)
543     CC1Args.append({"-include", "__clang_hip_runtime_wrapper.h"});
544 }
545 
546 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
547                                   const InputInfo &Output,
548                                   const InputInfoList &Inputs,
549                                   const ArgList &Args,
550                                   const char *LinkingOutput) const {
551 
552   std::string Linker = getToolChain().GetProgramPath(getShortName());
553   ArgStringList CmdArgs;
554   addLinkerCompressDebugSectionsOption(getToolChain(), Args, CmdArgs);
555   Args.AddAllArgs(CmdArgs, options::OPT_L);
556   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
557   if (C.getDriver().isUsingLTO())
558     addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
559                   C.getDriver().getLTOMode() == LTOK_Thin);
560   else if (Args.hasArg(options::OPT_mcpu_EQ))
561     CmdArgs.push_back(Args.MakeArgString(
562         "-plugin-opt=mcpu=" + Args.getLastArgValue(options::OPT_mcpu_EQ)));
563   CmdArgs.push_back("--no-undefined");
564   CmdArgs.push_back("-shared");
565   CmdArgs.push_back("-o");
566   CmdArgs.push_back(Output.getFilename());
567   C.addCommand(std::make_unique<Command>(
568       JA, *this, ResponseFileSupport::AtFileCurCP(), Args.MakeArgString(Linker),
569       CmdArgs, Inputs, Output));
570 }
571 
572 void amdgpu::getAMDGPUTargetFeatures(const Driver &D,
573                                      const llvm::Triple &Triple,
574                                      const llvm::opt::ArgList &Args,
575                                      std::vector<StringRef> &Features) {
576   // Add target ID features to -target-feature options. No diagnostics should
577   // be emitted here since invalid target ID is diagnosed at other places.
578   StringRef TargetID = Args.getLastArgValue(options::OPT_mcpu_EQ);
579   if (!TargetID.empty()) {
580     llvm::StringMap<bool> FeatureMap;
581     auto OptionalGpuArch = parseTargetID(Triple, TargetID, &FeatureMap);
582     if (OptionalGpuArch) {
583       StringRef GpuArch = *OptionalGpuArch;
584       // Iterate through all possible target ID features for the given GPU.
585       // If it is mapped to true, add +feature.
586       // If it is mapped to false, add -feature.
587       // If it is not in the map (default), do not add it
588       for (auto &&Feature : getAllPossibleTargetIDFeatures(Triple, GpuArch)) {
589         auto Pos = FeatureMap.find(Feature);
590         if (Pos == FeatureMap.end())
591           continue;
592         Features.push_back(Args.MakeArgStringRef(
593             (Twine(Pos->second ? "+" : "-") + Feature).str()));
594       }
595     }
596   }
597 
598   if (Args.hasFlag(options::OPT_mwavefrontsize64,
599                    options::OPT_mno_wavefrontsize64, false))
600     Features.push_back("+wavefrontsize64");
601 
602   handleTargetFeaturesGroup(D, Triple, Args, Features,
603                             options::OPT_m_amdgpu_Features_Group);
604 }
605 
606 /// AMDGPU Toolchain
607 AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
608                                  const ArgList &Args)
609     : Generic_ELF(D, Triple, Args),
610       OptionsDefault(
611           {{options::OPT_O, "3"}, {options::OPT_cl_std_EQ, "CL1.2"}}) {
612   // Check code object version options. Emit warnings for legacy options
613   // and errors for the last invalid code object version options.
614   // It is done here to avoid repeated warning or error messages for
615   // each tool invocation.
616   checkAMDGPUCodeObjectVersion(D, Args);
617 }
618 
619 Tool *AMDGPUToolChain::buildLinker() const {
620   return new tools::amdgpu::Linker(*this);
621 }
622 
623 DerivedArgList *
624 AMDGPUToolChain::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
625                                Action::OffloadKind DeviceOffloadKind) const {
626 
627   DerivedArgList *DAL =
628       Generic_ELF::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
629 
630   const OptTable &Opts = getDriver().getOpts();
631 
632   if (!DAL)
633     DAL = new DerivedArgList(Args.getBaseArgs());
634 
635   for (Arg *A : Args)
636     DAL->append(A);
637 
638   // Replace -mcpu=native with detected GPU.
639   Arg *LastMCPUArg = DAL->getLastArg(options::OPT_mcpu_EQ);
640   if (LastMCPUArg && StringRef(LastMCPUArg->getValue()) == "native") {
641     DAL->eraseArg(options::OPT_mcpu_EQ);
642     auto GPUsOrErr = getSystemGPUArchs(Args);
643     if (!GPUsOrErr) {
644       getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
645           << llvm::Triple::getArchTypeName(getArch())
646           << llvm::toString(GPUsOrErr.takeError()) << "-mcpu";
647     } else {
648       auto &GPUs = *GPUsOrErr;
649       if (GPUs.size() > 1) {
650         getDriver().Diag(diag::warn_drv_multi_gpu_arch)
651             << llvm::Triple::getArchTypeName(getArch())
652             << llvm::join(GPUs, ", ") << "-mcpu";
653       }
654       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mcpu_EQ),
655                         Args.MakeArgString(GPUs.front()));
656     }
657   }
658 
659   checkTargetID(*DAL);
660 
661   if (!Args.getLastArgValue(options::OPT_x).equals("cl"))
662     return DAL;
663 
664   // Phase 1 (.cl -> .bc)
665   if (Args.hasArg(options::OPT_c) && Args.hasArg(options::OPT_emit_llvm)) {
666     DAL->AddFlagArg(nullptr, Opts.getOption(getTriple().isArch64Bit()
667                                                 ? options::OPT_m64
668                                                 : options::OPT_m32));
669 
670     // Have to check OPT_O4, OPT_O0 & OPT_Ofast separately
671     // as they defined that way in Options.td
672     if (!Args.hasArg(options::OPT_O, options::OPT_O0, options::OPT_O4,
673                      options::OPT_Ofast))
674       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_O),
675                         getOptionDefault(options::OPT_O));
676   }
677 
678   return DAL;
679 }
680 
681 bool AMDGPUToolChain::getDefaultDenormsAreZeroForTarget(
682     llvm::AMDGPU::GPUKind Kind) {
683 
684   // Assume nothing without a specific target.
685   if (Kind == llvm::AMDGPU::GK_NONE)
686     return false;
687 
688   const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);
689 
690   // Default to enabling f32 denormals by default on subtargets where fma is
691   // fast with denormals
692   const bool BothDenormAndFMAFast =
693       (ArchAttr & llvm::AMDGPU::FEATURE_FAST_FMA_F32) &&
694       (ArchAttr & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32);
695   return !BothDenormAndFMAFast;
696 }
697 
698 llvm::DenormalMode AMDGPUToolChain::getDefaultDenormalModeForType(
699     const llvm::opt::ArgList &DriverArgs, const JobAction &JA,
700     const llvm::fltSemantics *FPType) const {
701   // Denormals should always be enabled for f16 and f64.
702   if (!FPType || FPType != &llvm::APFloat::IEEEsingle())
703     return llvm::DenormalMode::getIEEE();
704 
705   if (JA.getOffloadingDeviceKind() == Action::OFK_HIP ||
706       JA.getOffloadingDeviceKind() == Action::OFK_Cuda) {
707     auto Arch = getProcessorFromTargetID(getTriple(), JA.getOffloadingArch());
708     auto Kind = llvm::AMDGPU::parseArchAMDGCN(Arch);
709     if (FPType && FPType == &llvm::APFloat::IEEEsingle() &&
710         DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,
711                            options::OPT_fno_gpu_flush_denormals_to_zero,
712                            getDefaultDenormsAreZeroForTarget(Kind)))
713       return llvm::DenormalMode::getPreserveSign();
714 
715     return llvm::DenormalMode::getIEEE();
716   }
717 
718   const StringRef GpuArch = getGPUArch(DriverArgs);
719   auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);
720 
721   // TODO: There are way too many flags that change this. Do we need to check
722   // them all?
723   bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||
724              getDefaultDenormsAreZeroForTarget(Kind);
725 
726   // Outputs are flushed to zero (FTZ), preserving sign. Denormal inputs are
727   // also implicit treated as zero (DAZ).
728   return DAZ ? llvm::DenormalMode::getPreserveSign() :
729                llvm::DenormalMode::getIEEE();
730 }
731 
732 bool AMDGPUToolChain::isWave64(const llvm::opt::ArgList &DriverArgs,
733                                llvm::AMDGPU::GPUKind Kind) {
734   const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);
735   bool HasWave32 = (ArchAttr & llvm::AMDGPU::FEATURE_WAVE32);
736 
737   return !HasWave32 || DriverArgs.hasFlag(
738     options::OPT_mwavefrontsize64, options::OPT_mno_wavefrontsize64, false);
739 }
740 
741 
742 /// ROCM Toolchain
743 ROCMToolChain::ROCMToolChain(const Driver &D, const llvm::Triple &Triple,
744                              const ArgList &Args)
745     : AMDGPUToolChain(D, Triple, Args) {
746   RocmInstallation->detectDeviceLibrary();
747 }
748 
749 void AMDGPUToolChain::addClangTargetOptions(
750     const llvm::opt::ArgList &DriverArgs,
751     llvm::opt::ArgStringList &CC1Args,
752     Action::OffloadKind DeviceOffloadingKind) const {
753   // Default to "hidden" visibility, as object level linking will not be
754   // supported for the foreseeable future.
755   if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
756                          options::OPT_fvisibility_ms_compat)) {
757     CC1Args.push_back("-fvisibility=hidden");
758     CC1Args.push_back("-fapply-global-visibility-to-externs");
759   }
760 }
761 
762 StringRef
763 AMDGPUToolChain::getGPUArch(const llvm::opt::ArgList &DriverArgs) const {
764   return getProcessorFromTargetID(
765       getTriple(), DriverArgs.getLastArgValue(options::OPT_mcpu_EQ));
766 }
767 
768 AMDGPUToolChain::ParsedTargetIDType
769 AMDGPUToolChain::getParsedTargetID(const llvm::opt::ArgList &DriverArgs) const {
770   StringRef TargetID = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ);
771   if (TargetID.empty())
772     return {std::nullopt, std::nullopt, std::nullopt};
773 
774   llvm::StringMap<bool> FeatureMap;
775   auto OptionalGpuArch = parseTargetID(getTriple(), TargetID, &FeatureMap);
776   if (!OptionalGpuArch)
777     return {TargetID.str(), std::nullopt, std::nullopt};
778 
779   return {TargetID.str(), OptionalGpuArch->str(), FeatureMap};
780 }
781 
782 void AMDGPUToolChain::checkTargetID(
783     const llvm::opt::ArgList &DriverArgs) const {
784   auto PTID = getParsedTargetID(DriverArgs);
785   if (PTID.OptionalTargetID && !PTID.OptionalGPUArch) {
786     getDriver().Diag(clang::diag::err_drv_bad_target_id)
787         << *PTID.OptionalTargetID;
788   }
789 }
790 
791 Expected<SmallVector<std::string>>
792 AMDGPUToolChain::getSystemGPUArchs(const ArgList &Args) const {
793   // Detect AMD GPUs availible on the system.
794   std::string Program;
795   if (Arg *A = Args.getLastArg(options::OPT_amdgpu_arch_tool_EQ))
796     Program = A->getValue();
797   else
798     Program = GetProgramPath("amdgpu-arch");
799 
800   auto StdoutOrErr = executeToolChainProgram(Program);
801   if (!StdoutOrErr)
802     return StdoutOrErr.takeError();
803 
804   SmallVector<std::string, 1> GPUArchs;
805   for (StringRef Arch : llvm::split((*StdoutOrErr)->getBuffer(), "\n"))
806     if (!Arch.empty())
807       GPUArchs.push_back(Arch.str());
808 
809   if (GPUArchs.empty())
810     return llvm::createStringError(std::error_code(),
811                                    "No AMD GPU detected in the system");
812 
813   return std::move(GPUArchs);
814 }
815 
816 void ROCMToolChain::addClangTargetOptions(
817     const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
818     Action::OffloadKind DeviceOffloadingKind) const {
819   AMDGPUToolChain::addClangTargetOptions(DriverArgs, CC1Args,
820                                          DeviceOffloadingKind);
821 
822   // For the OpenCL case where there is no offload target, accept -nostdlib to
823   // disable bitcode linking.
824   if (DeviceOffloadingKind == Action::OFK_None &&
825       DriverArgs.hasArg(options::OPT_nostdlib))
826     return;
827 
828   if (DriverArgs.hasArg(options::OPT_nogpulib))
829     return;
830 
831   // Get the device name and canonicalize it
832   const StringRef GpuArch = getGPUArch(DriverArgs);
833   auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);
834   const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);
835   StringRef LibDeviceFile = RocmInstallation->getLibDeviceFile(CanonArch);
836   auto ABIVer = DeviceLibABIVersion::fromCodeObjectVersion(
837       getAMDGPUCodeObjectVersion(getDriver(), DriverArgs));
838   if (!RocmInstallation->checkCommonBitcodeLibs(CanonArch, LibDeviceFile,
839                                                 ABIVer))
840     return;
841 
842   bool Wave64 = isWave64(DriverArgs, Kind);
843 
844   // TODO: There are way too many flags that change this. Do we need to check
845   // them all?
846   bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||
847              getDefaultDenormsAreZeroForTarget(Kind);
848   bool FiniteOnly = DriverArgs.hasArg(options::OPT_cl_finite_math_only);
849 
850   bool UnsafeMathOpt =
851       DriverArgs.hasArg(options::OPT_cl_unsafe_math_optimizations);
852   bool FastRelaxedMath = DriverArgs.hasArg(options::OPT_cl_fast_relaxed_math);
853   bool CorrectSqrt =
854       DriverArgs.hasArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt);
855 
856   // Add the OpenCL specific bitcode library.
857   llvm::SmallVector<std::string, 12> BCLibs;
858   BCLibs.push_back(RocmInstallation->getOpenCLPath().str());
859 
860   // Add the generic set of libraries.
861   BCLibs.append(RocmInstallation->getCommonBitcodeLibs(
862       DriverArgs, LibDeviceFile, Wave64, DAZ, FiniteOnly, UnsafeMathOpt,
863       FastRelaxedMath, CorrectSqrt, ABIVer, false));
864 
865   for (StringRef BCFile : BCLibs) {
866     CC1Args.push_back("-mlink-builtin-bitcode");
867     CC1Args.push_back(DriverArgs.MakeArgString(BCFile));
868   }
869 }
870 
871 bool RocmInstallationDetector::checkCommonBitcodeLibs(
872     StringRef GPUArch, StringRef LibDeviceFile,
873     DeviceLibABIVersion ABIVer) const {
874   if (!hasDeviceLibrary()) {
875     D.Diag(diag::err_drv_no_rocm_device_lib) << 0;
876     return false;
877   }
878   if (LibDeviceFile.empty()) {
879     D.Diag(diag::err_drv_no_rocm_device_lib) << 1 << GPUArch;
880     return false;
881   }
882   if (ABIVer.requiresLibrary() && getABIVersionPath(ABIVer).empty()) {
883     D.Diag(diag::err_drv_no_rocm_device_lib) << 2 << ABIVer.toString();
884     return false;
885   }
886   return true;
887 }
888 
889 llvm::SmallVector<std::string, 12>
890 RocmInstallationDetector::getCommonBitcodeLibs(
891     const llvm::opt::ArgList &DriverArgs, StringRef LibDeviceFile, bool Wave64,
892     bool DAZ, bool FiniteOnly, bool UnsafeMathOpt, bool FastRelaxedMath,
893     bool CorrectSqrt, DeviceLibABIVersion ABIVer, bool isOpenMP = false) const {
894   llvm::SmallVector<std::string, 12> BCLibs;
895 
896   auto AddBCLib = [&](StringRef BCFile) { BCLibs.push_back(BCFile.str()); };
897 
898   AddBCLib(getOCMLPath());
899   AddBCLib(getOCKLPath());
900   AddBCLib(getDenormalsAreZeroPath(DAZ));
901   AddBCLib(getUnsafeMathPath(UnsafeMathOpt || FastRelaxedMath));
902   AddBCLib(getFiniteOnlyPath(FiniteOnly || FastRelaxedMath));
903   AddBCLib(getCorrectlyRoundedSqrtPath(CorrectSqrt));
904   AddBCLib(getWavefrontSize64Path(Wave64));
905   AddBCLib(LibDeviceFile);
906   auto ABIVerPath = getABIVersionPath(ABIVer);
907   if (!ABIVerPath.empty())
908     AddBCLib(ABIVerPath);
909 
910   return BCLibs;
911 }
912 
913 llvm::SmallVector<std::string, 12>
914 ROCMToolChain::getCommonDeviceLibNames(const llvm::opt::ArgList &DriverArgs,
915                                        const std::string &GPUArch,
916                                        bool isOpenMP) const {
917   auto Kind = llvm::AMDGPU::parseArchAMDGCN(GPUArch);
918   const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);
919 
920   StringRef LibDeviceFile = RocmInstallation->getLibDeviceFile(CanonArch);
921   auto ABIVer = DeviceLibABIVersion::fromCodeObjectVersion(
922       getAMDGPUCodeObjectVersion(getDriver(), DriverArgs));
923   if (!RocmInstallation->checkCommonBitcodeLibs(CanonArch, LibDeviceFile,
924                                                 ABIVer))
925     return {};
926 
927   // If --hip-device-lib is not set, add the default bitcode libraries.
928   // TODO: There are way too many flags that change this. Do we need to check
929   // them all?
930   bool DAZ = DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,
931                                 options::OPT_fno_gpu_flush_denormals_to_zero,
932                                 getDefaultDenormsAreZeroForTarget(Kind));
933   bool FiniteOnly = DriverArgs.hasFlag(
934       options::OPT_ffinite_math_only, options::OPT_fno_finite_math_only, false);
935   bool UnsafeMathOpt =
936       DriverArgs.hasFlag(options::OPT_funsafe_math_optimizations,
937                          options::OPT_fno_unsafe_math_optimizations, false);
938   bool FastRelaxedMath = DriverArgs.hasFlag(options::OPT_ffast_math,
939                                             options::OPT_fno_fast_math, false);
940   bool CorrectSqrt = DriverArgs.hasFlag(
941       options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
942       options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt, true);
943   bool Wave64 = isWave64(DriverArgs, Kind);
944 
945   return RocmInstallation->getCommonBitcodeLibs(
946       DriverArgs, LibDeviceFile, Wave64, DAZ, FiniteOnly, UnsafeMathOpt,
947       FastRelaxedMath, CorrectSqrt, ABIVer, isOpenMP);
948 }
949