Path: blob/main/contrib/llvm-project/clang/lib/Driver/ToolChains/AMDGPU.cpp
35294 views
//===--- AMDGPU.cpp - AMDGPU ToolChain Implementations ----------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "AMDGPU.h"9#include "CommonArgs.h"10#include "clang/Basic/TargetID.h"11#include "clang/Config/config.h"12#include "clang/Driver/Compilation.h"13#include "clang/Driver/DriverDiagnostic.h"14#include "clang/Driver/InputInfo.h"15#include "clang/Driver/Options.h"16#include "clang/Driver/SanitizerArgs.h"17#include "llvm/ADT/StringExtras.h"18#include "llvm/Option/ArgList.h"19#include "llvm/Support/Error.h"20#include "llvm/Support/LineIterator.h"21#include "llvm/Support/Path.h"22#include "llvm/Support/Process.h"23#include "llvm/Support/VirtualFileSystem.h"24#include "llvm/TargetParser/Host.h"25#include <optional>26#include <system_error>2728using namespace clang::driver;29using namespace clang::driver::tools;30using namespace clang::driver::toolchains;31using namespace clang;32using namespace llvm::opt;3334// Look for sub-directory starts with PackageName under ROCm candidate path.35// If there is one and only one matching sub-directory found, append the36// sub-directory to Path. If there is no matching sub-directory or there are37// more than one matching sub-directories, diagnose them. Returns the full38// path of the package if there is only one matching sub-directory, otherwise39// returns an empty string.40llvm::SmallString<0>41RocmInstallationDetector::findSPACKPackage(const Candidate &Cand,42StringRef PackageName) {43if (!Cand.isSPACK())44return {};45std::error_code EC;46std::string Prefix = Twine(PackageName + "-" + Cand.SPACKReleaseStr).str();47llvm::SmallVector<llvm::SmallString<0>> SubDirs;48for (llvm::vfs::directory_iterator File = D.getVFS().dir_begin(Cand.Path, EC),49FileEnd;50File != FileEnd && !EC; File.increment(EC)) {51llvm::StringRef FileName = llvm::sys::path::filename(File->path());52if (FileName.starts_with(Prefix)) {53SubDirs.push_back(FileName);54if (SubDirs.size() > 1)55break;56}57}58if (SubDirs.size() == 1) {59auto PackagePath = Cand.Path;60llvm::sys::path::append(PackagePath, SubDirs[0]);61return PackagePath;62}63if (SubDirs.size() == 0 && Verbose) {64llvm::errs() << "SPACK package " << Prefix << " not found at " << Cand.Path65<< '\n';66return {};67}6869if (SubDirs.size() > 1 && Verbose) {70llvm::errs() << "Cannot use SPACK package " << Prefix << " at " << Cand.Path71<< " due to multiple installations for the same version\n";72}73return {};74}7576void RocmInstallationDetector::scanLibDevicePath(llvm::StringRef Path) {77assert(!Path.empty());7879const StringRef Suffix(".bc");80const StringRef Suffix2(".amdgcn.bc");8182std::error_code EC;83for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(Path, EC), LE;84!EC && LI != LE; LI = LI.increment(EC)) {85StringRef FilePath = LI->path();86StringRef FileName = llvm::sys::path::filename(FilePath);87if (!FileName.ends_with(Suffix))88continue;8990StringRef BaseName;91if (FileName.ends_with(Suffix2))92BaseName = FileName.drop_back(Suffix2.size());93else if (FileName.ends_with(Suffix))94BaseName = FileName.drop_back(Suffix.size());9596const StringRef ABIVersionPrefix = "oclc_abi_version_";97if (BaseName == "ocml") {98OCML = FilePath;99} else if (BaseName == "ockl") {100OCKL = FilePath;101} else if (BaseName == "opencl") {102OpenCL = FilePath;103} else if (BaseName == "hip") {104HIP = FilePath;105} else if (BaseName == "asanrtl") {106AsanRTL = FilePath;107} else if (BaseName == "oclc_finite_only_off") {108FiniteOnly.Off = FilePath;109} else if (BaseName == "oclc_finite_only_on") {110FiniteOnly.On = FilePath;111} else if (BaseName == "oclc_daz_opt_on") {112DenormalsAreZero.On = FilePath;113} else if (BaseName == "oclc_daz_opt_off") {114DenormalsAreZero.Off = FilePath;115} else if (BaseName == "oclc_correctly_rounded_sqrt_on") {116CorrectlyRoundedSqrt.On = FilePath;117} else if (BaseName == "oclc_correctly_rounded_sqrt_off") {118CorrectlyRoundedSqrt.Off = FilePath;119} else if (BaseName == "oclc_unsafe_math_on") {120UnsafeMath.On = FilePath;121} else if (BaseName == "oclc_unsafe_math_off") {122UnsafeMath.Off = FilePath;123} else if (BaseName == "oclc_wavefrontsize64_on") {124WavefrontSize64.On = FilePath;125} else if (BaseName == "oclc_wavefrontsize64_off") {126WavefrontSize64.Off = FilePath;127} else if (BaseName.starts_with(ABIVersionPrefix)) {128unsigned ABIVersionNumber;129if (BaseName.drop_front(ABIVersionPrefix.size())130.getAsInteger(/*Redex=*/0, ABIVersionNumber))131continue;132ABIVersionMap[ABIVersionNumber] = FilePath.str();133} else {134// Process all bitcode filenames that look like135// ocl_isa_version_XXX.amdgcn.bc136const StringRef DeviceLibPrefix = "oclc_isa_version_";137if (!BaseName.starts_with(DeviceLibPrefix))138continue;139140StringRef IsaVersionNumber =141BaseName.drop_front(DeviceLibPrefix.size());142143llvm::Twine GfxName = Twine("gfx") + IsaVersionNumber;144SmallString<8> Tmp;145LibDeviceMap.insert(146std::make_pair(GfxName.toStringRef(Tmp), FilePath.str()));147}148}149}150151// Parse and extract version numbers from `.hipVersion`. Return `true` if152// the parsing fails.153bool RocmInstallationDetector::parseHIPVersionFile(llvm::StringRef V) {154SmallVector<StringRef, 4> VersionParts;155V.split(VersionParts, '\n');156unsigned Major = ~0U;157unsigned Minor = ~0U;158for (auto Part : VersionParts) {159auto Splits = Part.rtrim().split('=');160if (Splits.first == "HIP_VERSION_MAJOR") {161if (Splits.second.getAsInteger(0, Major))162return true;163} else if (Splits.first == "HIP_VERSION_MINOR") {164if (Splits.second.getAsInteger(0, Minor))165return true;166} else if (Splits.first == "HIP_VERSION_PATCH")167VersionPatch = Splits.second.str();168}169if (Major == ~0U || Minor == ~0U)170return true;171VersionMajorMinor = llvm::VersionTuple(Major, Minor);172DetectedVersion =173(Twine(Major) + "." + Twine(Minor) + "." + VersionPatch).str();174return false;175}176177/// \returns a list of candidate directories for ROCm installation, which is178/// cached and populated only once.179const SmallVectorImpl<RocmInstallationDetector::Candidate> &180RocmInstallationDetector::getInstallationPathCandidates() {181182// Return the cached candidate list if it has already been populated.183if (!ROCmSearchDirs.empty())184return ROCmSearchDirs;185186auto DoPrintROCmSearchDirs = [&]() {187if (PrintROCmSearchDirs)188for (auto Cand : ROCmSearchDirs) {189llvm::errs() << "ROCm installation search path";190if (Cand.isSPACK())191llvm::errs() << " (Spack " << Cand.SPACKReleaseStr << ")";192llvm::errs() << ": " << Cand.Path << '\n';193}194};195196// For candidate specified by --rocm-path we do not do strict check, i.e.,197// checking existence of HIP version file and device library files.198if (!RocmPathArg.empty()) {199ROCmSearchDirs.emplace_back(RocmPathArg.str());200DoPrintROCmSearchDirs();201return ROCmSearchDirs;202} else if (std::optional<std::string> RocmPathEnv =203llvm::sys::Process::GetEnv("ROCM_PATH")) {204if (!RocmPathEnv->empty()) {205ROCmSearchDirs.emplace_back(std::move(*RocmPathEnv));206DoPrintROCmSearchDirs();207return ROCmSearchDirs;208}209}210211// Try to find relative to the compiler binary.212StringRef InstallDir = D.Dir;213214// Check both a normal Unix prefix position of the clang binary, as well as215// the Windows-esque layout the ROCm packages use with the host architecture216// subdirectory of bin.217auto DeduceROCmPath = [](StringRef ClangPath) {218// Strip off directory (usually bin)219StringRef ParentDir = llvm::sys::path::parent_path(ClangPath);220StringRef ParentName = llvm::sys::path::filename(ParentDir);221222// Some builds use bin/{host arch}, so go up again.223if (ParentName == "bin") {224ParentDir = llvm::sys::path::parent_path(ParentDir);225ParentName = llvm::sys::path::filename(ParentDir);226}227228// Detect ROCm packages built with SPACK.229// clang is installed at230// <rocm_root>/llvm-amdgpu-<rocm_release_string>-<hash>/bin directory.231// We only consider the parent directory of llvm-amdgpu package as ROCm232// installation candidate for SPACK.233if (ParentName.starts_with("llvm-amdgpu-")) {234auto SPACKPostfix =235ParentName.drop_front(strlen("llvm-amdgpu-")).split('-');236auto SPACKReleaseStr = SPACKPostfix.first;237if (!SPACKReleaseStr.empty()) {238ParentDir = llvm::sys::path::parent_path(ParentDir);239return Candidate(ParentDir.str(), /*StrictChecking=*/true,240SPACKReleaseStr);241}242}243244// Some versions of the rocm llvm package install to /opt/rocm/llvm/bin245// Some versions of the aomp package install to /opt/rocm/aomp/bin246if (ParentName == "llvm" || ParentName.starts_with("aomp"))247ParentDir = llvm::sys::path::parent_path(ParentDir);248249return Candidate(ParentDir.str(), /*StrictChecking=*/true);250};251252// Deduce ROCm path by the path used to invoke clang. Do not resolve symbolic253// link of clang itself.254ROCmSearchDirs.emplace_back(DeduceROCmPath(InstallDir));255256// Deduce ROCm path by the real path of the invoked clang, resolving symbolic257// link of clang itself.258llvm::SmallString<256> RealClangPath;259llvm::sys::fs::real_path(D.getClangProgramPath(), RealClangPath);260auto ParentPath = llvm::sys::path::parent_path(RealClangPath);261if (ParentPath != InstallDir)262ROCmSearchDirs.emplace_back(DeduceROCmPath(ParentPath));263264// Device library may be installed in clang or resource directory.265auto ClangRoot = llvm::sys::path::parent_path(InstallDir);266auto RealClangRoot = llvm::sys::path::parent_path(ParentPath);267ROCmSearchDirs.emplace_back(ClangRoot.str(), /*StrictChecking=*/true);268if (RealClangRoot != ClangRoot)269ROCmSearchDirs.emplace_back(RealClangRoot.str(), /*StrictChecking=*/true);270ROCmSearchDirs.emplace_back(D.ResourceDir,271/*StrictChecking=*/true);272273ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/rocm",274/*StrictChecking=*/true);275276// Find the latest /opt/rocm-{release} directory.277std::error_code EC;278std::string LatestROCm;279llvm::VersionTuple LatestVer;280// Get ROCm version from ROCm directory name.281auto GetROCmVersion = [](StringRef DirName) {282llvm::VersionTuple V;283std::string VerStr = DirName.drop_front(strlen("rocm-")).str();284// The ROCm directory name follows the format of285// rocm-{major}.{minor}.{subMinor}[-{build}]286std::replace(VerStr.begin(), VerStr.end(), '-', '.');287V.tryParse(VerStr);288return V;289};290for (llvm::vfs::directory_iterator291File = D.getVFS().dir_begin(D.SysRoot + "/opt", EC),292FileEnd;293File != FileEnd && !EC; File.increment(EC)) {294llvm::StringRef FileName = llvm::sys::path::filename(File->path());295if (!FileName.starts_with("rocm-"))296continue;297if (LatestROCm.empty()) {298LatestROCm = FileName.str();299LatestVer = GetROCmVersion(LatestROCm);300continue;301}302auto Ver = GetROCmVersion(FileName);303if (LatestVer < Ver) {304LatestROCm = FileName.str();305LatestVer = Ver;306}307}308if (!LatestROCm.empty())309ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/" + LatestROCm,310/*StrictChecking=*/true);311312ROCmSearchDirs.emplace_back(D.SysRoot + "/usr/local",313/*StrictChecking=*/true);314ROCmSearchDirs.emplace_back(D.SysRoot + "/usr",315/*StrictChecking=*/true);316317DoPrintROCmSearchDirs();318return ROCmSearchDirs;319}320321RocmInstallationDetector::RocmInstallationDetector(322const Driver &D, const llvm::Triple &HostTriple,323const llvm::opt::ArgList &Args, bool DetectHIPRuntime, bool DetectDeviceLib)324: D(D) {325Verbose = Args.hasArg(options::OPT_v);326RocmPathArg = Args.getLastArgValue(clang::driver::options::OPT_rocm_path_EQ);327PrintROCmSearchDirs =328Args.hasArg(clang::driver::options::OPT_print_rocm_search_dirs);329RocmDeviceLibPathArg =330Args.getAllArgValues(clang::driver::options::OPT_rocm_device_lib_path_EQ);331HIPPathArg = Args.getLastArgValue(clang::driver::options::OPT_hip_path_EQ);332HIPStdParPathArg =333Args.getLastArgValue(clang::driver::options::OPT_hipstdpar_path_EQ);334HasHIPStdParLibrary =335!HIPStdParPathArg.empty() && D.getVFS().exists(HIPStdParPathArg +336"/hipstdpar_lib.hpp");337HIPRocThrustPathArg =338Args.getLastArgValue(clang::driver::options::OPT_hipstdpar_thrust_path_EQ);339HasRocThrustLibrary = !HIPRocThrustPathArg.empty() &&340D.getVFS().exists(HIPRocThrustPathArg + "/thrust");341HIPRocPrimPathArg =342Args.getLastArgValue(clang::driver::options::OPT_hipstdpar_prim_path_EQ);343HasRocPrimLibrary = !HIPRocPrimPathArg.empty() &&344D.getVFS().exists(HIPRocPrimPathArg + "/rocprim");345346if (auto *A = Args.getLastArg(clang::driver::options::OPT_hip_version_EQ)) {347HIPVersionArg = A->getValue();348unsigned Major = ~0U;349unsigned Minor = ~0U;350SmallVector<StringRef, 3> Parts;351HIPVersionArg.split(Parts, '.');352if (Parts.size())353Parts[0].getAsInteger(0, Major);354if (Parts.size() > 1)355Parts[1].getAsInteger(0, Minor);356if (Parts.size() > 2)357VersionPatch = Parts[2].str();358if (VersionPatch.empty())359VersionPatch = "0";360if (Major != ~0U && Minor == ~0U)361Minor = 0;362if (Major == ~0U || Minor == ~0U)363D.Diag(diag::err_drv_invalid_value)364<< A->getAsString(Args) << HIPVersionArg;365366VersionMajorMinor = llvm::VersionTuple(Major, Minor);367DetectedVersion =368(Twine(Major) + "." + Twine(Minor) + "." + VersionPatch).str();369} else {370VersionPatch = DefaultVersionPatch;371VersionMajorMinor =372llvm::VersionTuple(DefaultVersionMajor, DefaultVersionMinor);373DetectedVersion = (Twine(DefaultVersionMajor) + "." +374Twine(DefaultVersionMinor) + "." + VersionPatch)375.str();376}377378if (DetectHIPRuntime)379detectHIPRuntime();380if (DetectDeviceLib)381detectDeviceLibrary();382}383384void RocmInstallationDetector::detectDeviceLibrary() {385assert(LibDevicePath.empty());386387if (!RocmDeviceLibPathArg.empty())388LibDevicePath = RocmDeviceLibPathArg[RocmDeviceLibPathArg.size() - 1];389else if (std::optional<std::string> LibPathEnv =390llvm::sys::Process::GetEnv("HIP_DEVICE_LIB_PATH"))391LibDevicePath = std::move(*LibPathEnv);392393auto &FS = D.getVFS();394if (!LibDevicePath.empty()) {395// Maintain compatability with HIP flag/envvar pointing directly at the396// bitcode library directory. This points directly at the library path instead397// of the rocm root installation.398if (!FS.exists(LibDevicePath))399return;400401scanLibDevicePath(LibDevicePath);402HasDeviceLibrary = allGenericLibsValid() && !LibDeviceMap.empty();403return;404}405406// Check device library exists at the given path.407auto CheckDeviceLib = [&](StringRef Path, bool StrictChecking) {408bool CheckLibDevice = (!NoBuiltinLibs || StrictChecking);409if (CheckLibDevice && !FS.exists(Path))410return false;411412scanLibDevicePath(Path);413414if (!NoBuiltinLibs) {415// Check that the required non-target libraries are all available.416if (!allGenericLibsValid())417return false;418419// Check that we have found at least one libdevice that we can link in420// if -nobuiltinlib hasn't been specified.421if (LibDeviceMap.empty())422return false;423}424return true;425};426427// Find device libraries in <LLVM_DIR>/lib/clang/<ver>/lib/amdgcn/bitcode428LibDevicePath = D.ResourceDir;429llvm::sys::path::append(LibDevicePath, CLANG_INSTALL_LIBDIR_BASENAME,430"amdgcn", "bitcode");431HasDeviceLibrary = CheckDeviceLib(LibDevicePath, true);432if (HasDeviceLibrary)433return;434435// Find device libraries in a legacy ROCm directory structure436// ${ROCM_ROOT}/amdgcn/bitcode/*437auto &ROCmDirs = getInstallationPathCandidates();438for (const auto &Candidate : ROCmDirs) {439LibDevicePath = Candidate.Path;440llvm::sys::path::append(LibDevicePath, "amdgcn", "bitcode");441HasDeviceLibrary = CheckDeviceLib(LibDevicePath, Candidate.StrictChecking);442if (HasDeviceLibrary)443return;444}445}446447void RocmInstallationDetector::detectHIPRuntime() {448SmallVector<Candidate, 4> HIPSearchDirs;449if (!HIPPathArg.empty())450HIPSearchDirs.emplace_back(HIPPathArg.str());451else if (std::optional<std::string> HIPPathEnv =452llvm::sys::Process::GetEnv("HIP_PATH")) {453if (!HIPPathEnv->empty())454HIPSearchDirs.emplace_back(std::move(*HIPPathEnv));455}456if (HIPSearchDirs.empty())457HIPSearchDirs.append(getInstallationPathCandidates());458auto &FS = D.getVFS();459460for (const auto &Candidate : HIPSearchDirs) {461InstallPath = Candidate.Path;462if (InstallPath.empty() || !FS.exists(InstallPath))463continue;464// HIP runtime built by SPACK is installed to465// <rocm_root>/hip-<rocm_release_string>-<hash> directory.466auto SPACKPath = findSPACKPackage(Candidate, "hip");467InstallPath = SPACKPath.empty() ? InstallPath : SPACKPath;468469BinPath = InstallPath;470llvm::sys::path::append(BinPath, "bin");471IncludePath = InstallPath;472llvm::sys::path::append(IncludePath, "include");473LibPath = InstallPath;474llvm::sys::path::append(LibPath, "lib");475SharePath = InstallPath;476llvm::sys::path::append(SharePath, "share");477478// Get parent of InstallPath and append "share"479SmallString<0> ParentSharePath = llvm::sys::path::parent_path(InstallPath);480llvm::sys::path::append(ParentSharePath, "share");481482auto Append = [](SmallString<0> &path, const Twine &a, const Twine &b = "",483const Twine &c = "", const Twine &d = "") {484SmallString<0> newpath = path;485llvm::sys::path::append(newpath, a, b, c, d);486return newpath;487};488// If HIP version file can be found and parsed, use HIP version from there.489std::vector<SmallString<0>> VersionFilePaths = {490Append(SharePath, "hip", "version"),491InstallPath != D.SysRoot + "/usr/local"492? Append(ParentSharePath, "hip", "version")493: SmallString<0>(),494Append(BinPath, ".hipVersion")};495496for (const auto &VersionFilePath : VersionFilePaths) {497if (VersionFilePath.empty())498continue;499llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =500FS.getBufferForFile(VersionFilePath);501if (!VersionFile)502continue;503if (HIPVersionArg.empty() && VersionFile)504if (parseHIPVersionFile((*VersionFile)->getBuffer()))505continue;506507HasHIPRuntime = true;508return;509}510// Otherwise, if -rocm-path is specified (no strict checking), use the511// default HIP version or specified by --hip-version.512if (!Candidate.StrictChecking) {513HasHIPRuntime = true;514return;515}516}517HasHIPRuntime = false;518}519520void RocmInstallationDetector::print(raw_ostream &OS) const {521if (hasHIPRuntime())522OS << "Found HIP installation: " << InstallPath << ", version "523<< DetectedVersion << '\n';524}525526void RocmInstallationDetector::AddHIPIncludeArgs(const ArgList &DriverArgs,527ArgStringList &CC1Args) const {528bool UsesRuntimeWrapper = VersionMajorMinor > llvm::VersionTuple(3, 5) &&529!DriverArgs.hasArg(options::OPT_nohipwrapperinc);530bool HasHipStdPar = DriverArgs.hasArg(options::OPT_hipstdpar);531532if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {533// HIP header includes standard library wrapper headers under clang534// cuda_wrappers directory. Since these wrapper headers include_next535// standard C++ headers, whereas libc++ headers include_next other clang536// headers. The include paths have to follow this order:537// - wrapper include path538// - standard C++ include path539// - other clang include path540// Since standard C++ and other clang include paths are added in other541// places after this function, here we only need to make sure wrapper542// include path is added.543//544// ROCm 3.5 does not fully support the wrapper headers. Therefore it needs545// a workaround.546SmallString<128> P(D.ResourceDir);547if (UsesRuntimeWrapper)548llvm::sys::path::append(P, "include", "cuda_wrappers");549CC1Args.push_back("-internal-isystem");550CC1Args.push_back(DriverArgs.MakeArgString(P));551}552553const auto HandleHipStdPar = [=, &DriverArgs, &CC1Args]() {554StringRef Inc = getIncludePath();555auto &FS = D.getVFS();556557if (!hasHIPStdParLibrary())558if (!HIPStdParPathArg.empty() ||559!FS.exists(Inc + "/thrust/system/hip/hipstdpar/hipstdpar_lib.hpp")) {560D.Diag(diag::err_drv_no_hipstdpar_lib);561return;562}563if (!HasRocThrustLibrary && !FS.exists(Inc + "/thrust")) {564D.Diag(diag::err_drv_no_hipstdpar_thrust_lib);565return;566}567if (!HasRocPrimLibrary && !FS.exists(Inc + "/rocprim")) {568D.Diag(diag::err_drv_no_hipstdpar_prim_lib);569return;570}571const char *ThrustPath;572if (HasRocThrustLibrary)573ThrustPath = DriverArgs.MakeArgString(HIPRocThrustPathArg);574else575ThrustPath = DriverArgs.MakeArgString(Inc + "/thrust");576577const char *HIPStdParPath;578if (hasHIPStdParLibrary())579HIPStdParPath = DriverArgs.MakeArgString(HIPStdParPathArg);580else581HIPStdParPath = DriverArgs.MakeArgString(StringRef(ThrustPath) +582"/system/hip/hipstdpar");583584const char *PrimPath;585if (HasRocPrimLibrary)586PrimPath = DriverArgs.MakeArgString(HIPRocPrimPathArg);587else588PrimPath = DriverArgs.MakeArgString(getIncludePath() + "/rocprim");589590CC1Args.append({"-idirafter", ThrustPath, "-idirafter", PrimPath,591"-idirafter", HIPStdParPath, "-include",592"hipstdpar_lib.hpp"});593};594595if (DriverArgs.hasArg(options::OPT_nogpuinc)) {596if (HasHipStdPar)597HandleHipStdPar();598599return;600}601602if (!hasHIPRuntime()) {603D.Diag(diag::err_drv_no_hip_runtime);604return;605}606607CC1Args.push_back("-idirafter");608CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));609if (UsesRuntimeWrapper)610CC1Args.append({"-include", "__clang_hip_runtime_wrapper.h"});611if (HasHipStdPar)612HandleHipStdPar();613}614615void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,616const InputInfo &Output,617const InputInfoList &Inputs,618const ArgList &Args,619const char *LinkingOutput) const {620std::string Linker = getToolChain().GetLinkerPath();621ArgStringList CmdArgs;622CmdArgs.push_back("--no-undefined");623CmdArgs.push_back("-shared");624625addLinkerCompressDebugSectionsOption(getToolChain(), Args, CmdArgs);626Args.AddAllArgs(CmdArgs, options::OPT_L);627getToolChain().AddFilePathLibArgs(Args, CmdArgs);628AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);629if (C.getDriver().isUsingLTO())630addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],631C.getDriver().getLTOMode() == LTOK_Thin);632else if (Args.hasArg(options::OPT_mcpu_EQ))633CmdArgs.push_back(Args.MakeArgString(634"-plugin-opt=mcpu=" + Args.getLastArgValue(options::OPT_mcpu_EQ)));635CmdArgs.push_back("-o");636CmdArgs.push_back(Output.getFilename());637C.addCommand(std::make_unique<Command>(638JA, *this, ResponseFileSupport::AtFileCurCP(), Args.MakeArgString(Linker),639CmdArgs, Inputs, Output));640}641642void amdgpu::getAMDGPUTargetFeatures(const Driver &D,643const llvm::Triple &Triple,644const llvm::opt::ArgList &Args,645std::vector<StringRef> &Features) {646// Add target ID features to -target-feature options. No diagnostics should647// be emitted here since invalid target ID is diagnosed at other places.648StringRef TargetID;649if (Args.hasArg(options::OPT_mcpu_EQ))650TargetID = Args.getLastArgValue(options::OPT_mcpu_EQ);651else if (Args.hasArg(options::OPT_march_EQ))652TargetID = Args.getLastArgValue(options::OPT_march_EQ);653if (!TargetID.empty()) {654llvm::StringMap<bool> FeatureMap;655auto OptionalGpuArch = parseTargetID(Triple, TargetID, &FeatureMap);656if (OptionalGpuArch) {657StringRef GpuArch = *OptionalGpuArch;658// Iterate through all possible target ID features for the given GPU.659// If it is mapped to true, add +feature.660// If it is mapped to false, add -feature.661// If it is not in the map (default), do not add it662for (auto &&Feature : getAllPossibleTargetIDFeatures(Triple, GpuArch)) {663auto Pos = FeatureMap.find(Feature);664if (Pos == FeatureMap.end())665continue;666Features.push_back(Args.MakeArgStringRef(667(Twine(Pos->second ? "+" : "-") + Feature).str()));668}669}670}671672if (Args.hasFlag(options::OPT_mwavefrontsize64,673options::OPT_mno_wavefrontsize64, false))674Features.push_back("+wavefrontsize64");675676if (Args.hasFlag(options::OPT_mamdgpu_precise_memory_op,677options::OPT_mno_amdgpu_precise_memory_op, false))678Features.push_back("+precise-memory");679680handleTargetFeaturesGroup(D, Triple, Args, Features,681options::OPT_m_amdgpu_Features_Group);682}683684/// AMDGPU Toolchain685AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,686const ArgList &Args)687: Generic_ELF(D, Triple, Args),688OptionsDefault(689{{options::OPT_O, "3"}, {options::OPT_cl_std_EQ, "CL1.2"}}) {690// Check code object version options. Emit warnings for legacy options691// and errors for the last invalid code object version options.692// It is done here to avoid repeated warning or error messages for693// each tool invocation.694checkAMDGPUCodeObjectVersion(D, Args);695}696697Tool *AMDGPUToolChain::buildLinker() const {698return new tools::amdgpu::Linker(*this);699}700701DerivedArgList *702AMDGPUToolChain::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,703Action::OffloadKind DeviceOffloadKind) const {704705DerivedArgList *DAL =706Generic_ELF::TranslateArgs(Args, BoundArch, DeviceOffloadKind);707708const OptTable &Opts = getDriver().getOpts();709710if (!DAL)711DAL = new DerivedArgList(Args.getBaseArgs());712713for (Arg *A : Args)714DAL->append(A);715716// Replace -mcpu=native with detected GPU.717Arg *LastMCPUArg = DAL->getLastArg(options::OPT_mcpu_EQ);718if (LastMCPUArg && StringRef(LastMCPUArg->getValue()) == "native") {719DAL->eraseArg(options::OPT_mcpu_EQ);720auto GPUsOrErr = getSystemGPUArchs(Args);721if (!GPUsOrErr) {722getDriver().Diag(diag::err_drv_undetermined_gpu_arch)723<< llvm::Triple::getArchTypeName(getArch())724<< llvm::toString(GPUsOrErr.takeError()) << "-mcpu";725} else {726auto &GPUs = *GPUsOrErr;727if (GPUs.size() > 1) {728getDriver().Diag(diag::warn_drv_multi_gpu_arch)729<< llvm::Triple::getArchTypeName(getArch())730<< llvm::join(GPUs, ", ") << "-mcpu";731}732DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mcpu_EQ),733Args.MakeArgString(GPUs.front()));734}735}736737checkTargetID(*DAL);738739if (Args.getLastArgValue(options::OPT_x) != "cl")740return DAL;741742// Phase 1 (.cl -> .bc)743if (Args.hasArg(options::OPT_c) && Args.hasArg(options::OPT_emit_llvm)) {744DAL->AddFlagArg(nullptr, Opts.getOption(getTriple().isArch64Bit()745? options::OPT_m64746: options::OPT_m32));747748// Have to check OPT_O4, OPT_O0 & OPT_Ofast separately749// as they defined that way in Options.td750if (!Args.hasArg(options::OPT_O, options::OPT_O0, options::OPT_O4,751options::OPT_Ofast))752DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_O),753getOptionDefault(options::OPT_O));754}755756return DAL;757}758759bool AMDGPUToolChain::getDefaultDenormsAreZeroForTarget(760llvm::AMDGPU::GPUKind Kind) {761762// Assume nothing without a specific target.763if (Kind == llvm::AMDGPU::GK_NONE)764return false;765766const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);767768// Default to enabling f32 denormals by default on subtargets where fma is769// fast with denormals770const bool BothDenormAndFMAFast =771(ArchAttr & llvm::AMDGPU::FEATURE_FAST_FMA_F32) &&772(ArchAttr & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32);773return !BothDenormAndFMAFast;774}775776llvm::DenormalMode AMDGPUToolChain::getDefaultDenormalModeForType(777const llvm::opt::ArgList &DriverArgs, const JobAction &JA,778const llvm::fltSemantics *FPType) const {779// Denormals should always be enabled for f16 and f64.780if (!FPType || FPType != &llvm::APFloat::IEEEsingle())781return llvm::DenormalMode::getIEEE();782783if (JA.getOffloadingDeviceKind() == Action::OFK_HIP ||784JA.getOffloadingDeviceKind() == Action::OFK_Cuda) {785auto Arch = getProcessorFromTargetID(getTriple(), JA.getOffloadingArch());786auto Kind = llvm::AMDGPU::parseArchAMDGCN(Arch);787if (FPType && FPType == &llvm::APFloat::IEEEsingle() &&788DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,789options::OPT_fno_gpu_flush_denormals_to_zero,790getDefaultDenormsAreZeroForTarget(Kind)))791return llvm::DenormalMode::getPreserveSign();792793return llvm::DenormalMode::getIEEE();794}795796const StringRef GpuArch = getGPUArch(DriverArgs);797auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);798799// TODO: There are way too many flags that change this. Do we need to check800// them all?801bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||802getDefaultDenormsAreZeroForTarget(Kind);803804// Outputs are flushed to zero (FTZ), preserving sign. Denormal inputs are805// also implicit treated as zero (DAZ).806return DAZ ? llvm::DenormalMode::getPreserveSign() :807llvm::DenormalMode::getIEEE();808}809810bool AMDGPUToolChain::isWave64(const llvm::opt::ArgList &DriverArgs,811llvm::AMDGPU::GPUKind Kind) {812const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);813bool HasWave32 = (ArchAttr & llvm::AMDGPU::FEATURE_WAVE32);814815return !HasWave32 || DriverArgs.hasFlag(816options::OPT_mwavefrontsize64, options::OPT_mno_wavefrontsize64, false);817}818819820/// ROCM Toolchain821ROCMToolChain::ROCMToolChain(const Driver &D, const llvm::Triple &Triple,822const ArgList &Args)823: AMDGPUToolChain(D, Triple, Args) {824RocmInstallation->detectDeviceLibrary();825}826827void AMDGPUToolChain::addClangTargetOptions(828const llvm::opt::ArgList &DriverArgs,829llvm::opt::ArgStringList &CC1Args,830Action::OffloadKind DeviceOffloadingKind) const {831// Default to "hidden" visibility, as object level linking will not be832// supported for the foreseeable future.833if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,834options::OPT_fvisibility_ms_compat)) {835CC1Args.push_back("-fvisibility=hidden");836CC1Args.push_back("-fapply-global-visibility-to-externs");837}838}839840void AMDGPUToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {841// AMDGPU does not support atomic lib call. Treat atomic alignment842// warnings as errors.843CC1Args.push_back("-Werror=atomic-alignment");844}845846StringRef847AMDGPUToolChain::getGPUArch(const llvm::opt::ArgList &DriverArgs) const {848return getProcessorFromTargetID(849getTriple(), DriverArgs.getLastArgValue(options::OPT_mcpu_EQ));850}851852AMDGPUToolChain::ParsedTargetIDType853AMDGPUToolChain::getParsedTargetID(const llvm::opt::ArgList &DriverArgs) const {854StringRef TargetID = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ);855if (TargetID.empty())856return {std::nullopt, std::nullopt, std::nullopt};857858llvm::StringMap<bool> FeatureMap;859auto OptionalGpuArch = parseTargetID(getTriple(), TargetID, &FeatureMap);860if (!OptionalGpuArch)861return {TargetID.str(), std::nullopt, std::nullopt};862863return {TargetID.str(), OptionalGpuArch->str(), FeatureMap};864}865866void AMDGPUToolChain::checkTargetID(867const llvm::opt::ArgList &DriverArgs) const {868auto PTID = getParsedTargetID(DriverArgs);869if (PTID.OptionalTargetID && !PTID.OptionalGPUArch) {870getDriver().Diag(clang::diag::err_drv_bad_target_id)871<< *PTID.OptionalTargetID;872}873}874875Expected<SmallVector<std::string>>876AMDGPUToolChain::getSystemGPUArchs(const ArgList &Args) const {877// Detect AMD GPUs availible on the system.878std::string Program;879if (Arg *A = Args.getLastArg(options::OPT_amdgpu_arch_tool_EQ))880Program = A->getValue();881else882Program = GetProgramPath("amdgpu-arch");883884auto StdoutOrErr = executeToolChainProgram(Program, /*SecondsToWait=*/10);885if (!StdoutOrErr)886return StdoutOrErr.takeError();887888SmallVector<std::string, 1> GPUArchs;889for (StringRef Arch : llvm::split((*StdoutOrErr)->getBuffer(), "\n"))890if (!Arch.empty())891GPUArchs.push_back(Arch.str());892893if (GPUArchs.empty())894return llvm::createStringError(std::error_code(),895"No AMD GPU detected in the system");896897return std::move(GPUArchs);898}899900void ROCMToolChain::addClangTargetOptions(901const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,902Action::OffloadKind DeviceOffloadingKind) const {903AMDGPUToolChain::addClangTargetOptions(DriverArgs, CC1Args,904DeviceOffloadingKind);905906// For the OpenCL case where there is no offload target, accept -nostdlib to907// disable bitcode linking.908if (DeviceOffloadingKind == Action::OFK_None &&909DriverArgs.hasArg(options::OPT_nostdlib))910return;911912if (DriverArgs.hasArg(options::OPT_nogpulib))913return;914915// Get the device name and canonicalize it916const StringRef GpuArch = getGPUArch(DriverArgs);917auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);918const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);919StringRef LibDeviceFile = RocmInstallation->getLibDeviceFile(CanonArch);920auto ABIVer = DeviceLibABIVersion::fromCodeObjectVersion(921getAMDGPUCodeObjectVersion(getDriver(), DriverArgs));922if (!RocmInstallation->checkCommonBitcodeLibs(CanonArch, LibDeviceFile,923ABIVer))924return;925926bool Wave64 = isWave64(DriverArgs, Kind);927928// TODO: There are way too many flags that change this. Do we need to check929// them all?930bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||931getDefaultDenormsAreZeroForTarget(Kind);932bool FiniteOnly = DriverArgs.hasArg(options::OPT_cl_finite_math_only);933934bool UnsafeMathOpt =935DriverArgs.hasArg(options::OPT_cl_unsafe_math_optimizations);936bool FastRelaxedMath = DriverArgs.hasArg(options::OPT_cl_fast_relaxed_math);937bool CorrectSqrt =938DriverArgs.hasArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt);939940// Add the OpenCL specific bitcode library.941llvm::SmallVector<std::string, 12> BCLibs;942BCLibs.push_back(RocmInstallation->getOpenCLPath().str());943944// Add the generic set of libraries.945BCLibs.append(RocmInstallation->getCommonBitcodeLibs(946DriverArgs, LibDeviceFile, Wave64, DAZ, FiniteOnly, UnsafeMathOpt,947FastRelaxedMath, CorrectSqrt, ABIVer, false));948949if (getSanitizerArgs(DriverArgs).needsAsanRt()) {950CC1Args.push_back("-mlink-bitcode-file");951CC1Args.push_back(952DriverArgs.MakeArgString(RocmInstallation->getAsanRTLPath()));953}954for (StringRef BCFile : BCLibs) {955CC1Args.push_back("-mlink-builtin-bitcode");956CC1Args.push_back(DriverArgs.MakeArgString(BCFile));957}958}959960bool RocmInstallationDetector::checkCommonBitcodeLibs(961StringRef GPUArch, StringRef LibDeviceFile,962DeviceLibABIVersion ABIVer) const {963if (!hasDeviceLibrary()) {964D.Diag(diag::err_drv_no_rocm_device_lib) << 0;965return false;966}967if (LibDeviceFile.empty()) {968D.Diag(diag::err_drv_no_rocm_device_lib) << 1 << GPUArch;969return false;970}971if (ABIVer.requiresLibrary() && getABIVersionPath(ABIVer).empty()) {972D.Diag(diag::err_drv_no_rocm_device_lib) << 2 << ABIVer.toString();973return false;974}975return true;976}977978llvm::SmallVector<std::string, 12>979RocmInstallationDetector::getCommonBitcodeLibs(980const llvm::opt::ArgList &DriverArgs, StringRef LibDeviceFile, bool Wave64,981bool DAZ, bool FiniteOnly, bool UnsafeMathOpt, bool FastRelaxedMath,982bool CorrectSqrt, DeviceLibABIVersion ABIVer, bool isOpenMP = false) const {983llvm::SmallVector<std::string, 12> BCLibs;984985auto AddBCLib = [&](StringRef BCFile) { BCLibs.push_back(BCFile.str()); };986987AddBCLib(getOCMLPath());988if (!isOpenMP)989AddBCLib(getOCKLPath());990AddBCLib(getDenormalsAreZeroPath(DAZ));991AddBCLib(getUnsafeMathPath(UnsafeMathOpt || FastRelaxedMath));992AddBCLib(getFiniteOnlyPath(FiniteOnly || FastRelaxedMath));993AddBCLib(getCorrectlyRoundedSqrtPath(CorrectSqrt));994AddBCLib(getWavefrontSize64Path(Wave64));995AddBCLib(LibDeviceFile);996auto ABIVerPath = getABIVersionPath(ABIVer);997if (!ABIVerPath.empty())998AddBCLib(ABIVerPath);9991000return BCLibs;1001}10021003llvm::SmallVector<std::string, 12>1004ROCMToolChain::getCommonDeviceLibNames(const llvm::opt::ArgList &DriverArgs,1005const std::string &GPUArch,1006bool isOpenMP) const {1007auto Kind = llvm::AMDGPU::parseArchAMDGCN(GPUArch);1008const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);10091010StringRef LibDeviceFile = RocmInstallation->getLibDeviceFile(CanonArch);1011auto ABIVer = DeviceLibABIVersion::fromCodeObjectVersion(1012getAMDGPUCodeObjectVersion(getDriver(), DriverArgs));1013if (!RocmInstallation->checkCommonBitcodeLibs(CanonArch, LibDeviceFile,1014ABIVer))1015return {};10161017// If --hip-device-lib is not set, add the default bitcode libraries.1018// TODO: There are way too many flags that change this. Do we need to check1019// them all?1020bool DAZ = DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,1021options::OPT_fno_gpu_flush_denormals_to_zero,1022getDefaultDenormsAreZeroForTarget(Kind));1023bool FiniteOnly = DriverArgs.hasFlag(1024options::OPT_ffinite_math_only, options::OPT_fno_finite_math_only, false);1025bool UnsafeMathOpt =1026DriverArgs.hasFlag(options::OPT_funsafe_math_optimizations,1027options::OPT_fno_unsafe_math_optimizations, false);1028bool FastRelaxedMath = DriverArgs.hasFlag(options::OPT_ffast_math,1029options::OPT_fno_fast_math, false);1030bool CorrectSqrt = DriverArgs.hasFlag(1031options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,1032options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt, true);1033bool Wave64 = isWave64(DriverArgs, Kind);10341035return RocmInstallation->getCommonBitcodeLibs(1036DriverArgs, LibDeviceFile, Wave64, DAZ, FiniteOnly, UnsafeMathOpt,1037FastRelaxedMath, CorrectSqrt, ABIVer, isOpenMP);1038}103910401041