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