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