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