Path: blob/main/contrib/llvm-project/clang/lib/Driver/ToolChains/HIPAMD.cpp
35266 views
//===--- HIPAMD.cpp - HIP Tool and 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 "HIPAMD.h"9#include "AMDGPU.h"10#include "CommonArgs.h"11#include "HIPUtility.h"12#include "SPIRV.h"13#include "clang/Basic/Cuda.h"14#include "clang/Basic/TargetID.h"15#include "clang/Driver/Compilation.h"16#include "clang/Driver/Driver.h"17#include "clang/Driver/DriverDiagnostic.h"18#include "clang/Driver/InputInfo.h"19#include "clang/Driver/Options.h"20#include "clang/Driver/SanitizerArgs.h"21#include "llvm/Support/Alignment.h"22#include "llvm/Support/FileSystem.h"23#include "llvm/Support/Path.h"24#include "llvm/TargetParser/TargetParser.h"2526using namespace clang::driver;27using namespace clang::driver::toolchains;28using namespace clang::driver::tools;29using namespace clang;30using namespace llvm::opt;3132#if defined(_WIN32) || defined(_WIN64)33#define NULL_FILE "nul"34#else35#define NULL_FILE "/dev/null"36#endif3738static bool shouldSkipSanitizeOption(const ToolChain &TC,39const llvm::opt::ArgList &DriverArgs,40StringRef TargetID,41const llvm::opt::Arg *A) {42// For actions without targetID, do nothing.43if (TargetID.empty())44return false;45Option O = A->getOption();46if (!O.matches(options::OPT_fsanitize_EQ))47return false;4849if (!DriverArgs.hasFlag(options::OPT_fgpu_sanitize,50options::OPT_fno_gpu_sanitize, true))51return true;5253auto &Diags = TC.getDriver().getDiags();5455// For simplicity, we only allow -fsanitize=address56SanitizerMask K = parseSanitizerValue(A->getValue(), /*AllowGroups=*/false);57if (K != SanitizerKind::Address)58return true;5960llvm::StringMap<bool> FeatureMap;61auto OptionalGpuArch = parseTargetID(TC.getTriple(), TargetID, &FeatureMap);6263assert(OptionalGpuArch && "Invalid Target ID");64(void)OptionalGpuArch;65auto Loc = FeatureMap.find("xnack");66if (Loc == FeatureMap.end() || !Loc->second) {67Diags.Report(68clang::diag::warn_drv_unsupported_option_for_offload_arch_req_feature)69<< A->getAsString(DriverArgs) << TargetID << "xnack+";70return true;71}72return false;73}7475void AMDGCN::Linker::constructLlvmLinkCommand(Compilation &C,76const JobAction &JA,77const InputInfoList &Inputs,78const InputInfo &Output,79const llvm::opt::ArgList &Args) const {80// Construct llvm-link command.81// The output from llvm-link is a bitcode file.82ArgStringList LlvmLinkArgs;8384assert(!Inputs.empty() && "Must have at least one input.");8586LlvmLinkArgs.append({"-o", Output.getFilename()});87for (auto Input : Inputs)88LlvmLinkArgs.push_back(Input.getFilename());8990// Look for archive of bundled bitcode in arguments, and add temporary files91// for the extracted archive of bitcode to inputs.92auto TargetID = Args.getLastArgValue(options::OPT_mcpu_EQ);93AddStaticDeviceLibsLinking(C, *this, JA, Inputs, Args, LlvmLinkArgs, "amdgcn",94TargetID, /*IsBitCodeSDL=*/true);9596const char *LlvmLink =97Args.MakeArgString(getToolChain().GetProgramPath("llvm-link"));98C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),99LlvmLink, LlvmLinkArgs, Inputs,100Output));101}102103void AMDGCN::Linker::constructLldCommand(Compilation &C, const JobAction &JA,104const InputInfoList &Inputs,105const InputInfo &Output,106const llvm::opt::ArgList &Args) const {107// Construct lld command.108// The output from ld.lld is an HSA code object file.109ArgStringList LldArgs{"-flavor",110"gnu",111"-m",112"elf64_amdgpu",113"--no-undefined",114"-shared",115"-plugin-opt=-amdgpu-internalize-symbols"};116if (Args.hasArg(options::OPT_hipstdpar))117LldArgs.push_back("-plugin-opt=-amdgpu-enable-hipstdpar");118119auto &TC = getToolChain();120auto &D = TC.getDriver();121assert(!Inputs.empty() && "Must have at least one input.");122bool IsThinLTO = D.getLTOMode(/*IsOffload=*/true) == LTOK_Thin;123addLTOOptions(TC, Args, LldArgs, Output, Inputs[0], IsThinLTO);124125// Extract all the -m options126std::vector<llvm::StringRef> Features;127amdgpu::getAMDGPUTargetFeatures(D, TC.getTriple(), Args, Features);128129// Add features to mattr such as cumode130std::string MAttrString = "-plugin-opt=-mattr=";131for (auto OneFeature : unifyTargetFeatures(Features)) {132MAttrString.append(Args.MakeArgString(OneFeature));133if (OneFeature != Features.back())134MAttrString.append(",");135}136if (!Features.empty())137LldArgs.push_back(Args.MakeArgString(MAttrString));138139// ToDo: Remove this option after AMDGPU backend supports ISA-level linking.140// Since AMDGPU backend currently does not support ISA-level linking, all141// called functions need to be imported.142if (IsThinLTO)143LldArgs.push_back(Args.MakeArgString("-plugin-opt=-force-import-all"));144145for (const Arg *A : Args.filtered(options::OPT_mllvm)) {146LldArgs.push_back(147Args.MakeArgString(Twine("-plugin-opt=") + A->getValue(0)));148}149150if (C.getDriver().isSaveTempsEnabled())151LldArgs.push_back("-save-temps");152153addLinkerCompressDebugSectionsOption(TC, Args, LldArgs);154155// Given that host and device linking happen in separate processes, the device156// linker doesn't always have the visibility as to which device symbols are157// needed by a program, especially for the device symbol dependencies that are158// introduced through the host symbol resolution.159// For example: host_A() (A.obj) --> host_B(B.obj) --> device_kernel_B()160// (B.obj) In this case, the device linker doesn't know that A.obj actually161// depends on the kernel functions in B.obj. When linking to static device162// library, the device linker may drop some of the device global symbols if163// they aren't referenced. As a workaround, we are adding to the164// --whole-archive flag such that all global symbols would be linked in.165LldArgs.push_back("--whole-archive");166167for (auto *Arg : Args.filtered(options::OPT_Xoffload_linker)) {168StringRef ArgVal = Arg->getValue(1);169auto SplitArg = ArgVal.split("-mllvm=");170if (!SplitArg.second.empty()) {171LldArgs.push_back(172Args.MakeArgString(Twine("-plugin-opt=") + SplitArg.second));173} else {174LldArgs.push_back(Args.MakeArgString(ArgVal));175}176Arg->claim();177}178179LldArgs.append({"-o", Output.getFilename()});180for (auto Input : Inputs)181LldArgs.push_back(Input.getFilename());182183// Look for archive of bundled bitcode in arguments, and add temporary files184// for the extracted archive of bitcode to inputs.185auto TargetID = Args.getLastArgValue(options::OPT_mcpu_EQ);186AddStaticDeviceLibsLinking(C, *this, JA, Inputs, Args, LldArgs, "amdgcn",187TargetID, /*IsBitCodeSDL=*/true);188189LldArgs.push_back("--no-whole-archive");190191const char *Lld = Args.MakeArgString(getToolChain().GetProgramPath("lld"));192C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),193Lld, LldArgs, Inputs, Output));194}195196// For SPIR-V the inputs for the job are device AMDGCN SPIR-V flavoured bitcode197// and the output is either a compiled SPIR-V binary or bitcode (-emit-llvm). It198// calls llvm-link and then the llvm-spirv translator. Once the SPIR-V BE will199// be promoted from experimental, we will switch to using that. TODO: consider200// if we want to run any targeted optimisations over IR here, over generic201// SPIR-V.202void AMDGCN::Linker::constructLinkAndEmitSpirvCommand(203Compilation &C, const JobAction &JA, const InputInfoList &Inputs,204const InputInfo &Output, const llvm::opt::ArgList &Args) const {205assert(!Inputs.empty() && "Must have at least one input.");206207constructLlvmLinkCommand(C, JA, Inputs, Output, Args);208209// Linked BC is now in Output210211// Emit SPIR-V binary.212llvm::opt::ArgStringList TrArgs{213"--spirv-max-version=1.6",214"--spirv-ext=+all",215"--spirv-allow-extra-diexpressions",216"--spirv-allow-unknown-intrinsics",217"--spirv-lower-const-expr",218"--spirv-preserve-auxdata",219"--spirv-debug-info-version=nonsemantic-shader-200"};220SPIRV::constructTranslateCommand(C, *this, JA, Output, Output, TrArgs);221}222223// For amdgcn the inputs of the linker job are device bitcode and output is224// either an object file or bitcode (-emit-llvm). It calls llvm-link, opt,225// llc, then lld steps.226void AMDGCN::Linker::ConstructJob(Compilation &C, const JobAction &JA,227const InputInfo &Output,228const InputInfoList &Inputs,229const ArgList &Args,230const char *LinkingOutput) const {231if (Inputs.size() > 0 &&232Inputs[0].getType() == types::TY_Image &&233JA.getType() == types::TY_Object)234return HIP::constructGenerateObjFileFromHIPFatBinary(C, Output, Inputs,235Args, JA, *this);236237if (JA.getType() == types::TY_HIP_FATBIN)238return HIP::constructHIPFatbinCommand(C, JA, Output.getFilename(), Inputs,239Args, *this);240241if (JA.getType() == types::TY_LLVM_BC)242return constructLlvmLinkCommand(C, JA, Inputs, Output, Args);243244if (getToolChain().getTriple().isSPIRV())245return constructLinkAndEmitSpirvCommand(C, JA, Inputs, Output, Args);246247return constructLldCommand(C, JA, Inputs, Output, Args);248}249250HIPAMDToolChain::HIPAMDToolChain(const Driver &D, const llvm::Triple &Triple,251const ToolChain &HostTC, const ArgList &Args)252: ROCMToolChain(D, Triple, Args), HostTC(HostTC) {253// Lookup binaries into the driver directory, this is used to254// discover the clang-offload-bundler executable.255getProgramPaths().push_back(getDriver().Dir);256257// Diagnose unsupported sanitizer options only once.258if (!Args.hasFlag(options::OPT_fgpu_sanitize, options::OPT_fno_gpu_sanitize,259true))260return;261for (auto *A : Args.filtered(options::OPT_fsanitize_EQ)) {262SanitizerMask K = parseSanitizerValue(A->getValue(), /*AllowGroups=*/false);263if (K != SanitizerKind::Address)264D.getDiags().Report(clang::diag::warn_drv_unsupported_option_for_target)265<< A->getAsString(Args) << getTriple().str();266}267}268269void HIPAMDToolChain::addClangTargetOptions(270const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,271Action::OffloadKind DeviceOffloadingKind) const {272HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);273274assert(DeviceOffloadingKind == Action::OFK_HIP &&275"Only HIP offloading kinds are supported for GPUs.");276277CC1Args.push_back("-fcuda-is-device");278279if (!DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,280false))281CC1Args.append({"-mllvm", "-amdgpu-internalize-symbols"});282if (DriverArgs.hasArgNoClaim(options::OPT_hipstdpar))283CC1Args.append({"-mllvm", "-amdgpu-enable-hipstdpar"});284285StringRef MaxThreadsPerBlock =286DriverArgs.getLastArgValue(options::OPT_gpu_max_threads_per_block_EQ);287if (!MaxThreadsPerBlock.empty()) {288std::string ArgStr =289(Twine("--gpu-max-threads-per-block=") + MaxThreadsPerBlock).str();290CC1Args.push_back(DriverArgs.MakeArgStringRef(ArgStr));291}292293CC1Args.push_back("-fcuda-allow-variadic-functions");294295// Default to "hidden" visibility, as object level linking will not be296// supported for the foreseeable future.297if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,298options::OPT_fvisibility_ms_compat)) {299CC1Args.append({"-fvisibility=hidden"});300CC1Args.push_back("-fapply-global-visibility-to-externs");301}302303// For SPIR-V we embed the command-line into the generated binary, in order to304// retrieve it at JIT time and be able to do target specific compilation with305// options that match the user-supplied ones.306if (getTriple().isSPIRV() &&307!DriverArgs.hasArg(options::OPT_fembed_bitcode_marker))308CC1Args.push_back("-fembed-bitcode=marker");309310for (auto BCFile : getDeviceLibs(DriverArgs)) {311CC1Args.push_back(BCFile.ShouldInternalize ? "-mlink-builtin-bitcode"312: "-mlink-bitcode-file");313CC1Args.push_back(DriverArgs.MakeArgString(BCFile.Path));314}315}316317llvm::opt::DerivedArgList *318HIPAMDToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,319StringRef BoundArch,320Action::OffloadKind DeviceOffloadKind) const {321DerivedArgList *DAL =322HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);323if (!DAL)324DAL = new DerivedArgList(Args.getBaseArgs());325326const OptTable &Opts = getDriver().getOpts();327328for (Arg *A : Args) {329if (!shouldSkipSanitizeOption(*this, Args, BoundArch, A))330DAL->append(A);331}332333if (!BoundArch.empty()) {334DAL->eraseArg(options::OPT_mcpu_EQ);335DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mcpu_EQ), BoundArch);336checkTargetID(*DAL);337}338339return DAL;340}341342Tool *HIPAMDToolChain::buildLinker() const {343assert(getTriple().getArch() == llvm::Triple::amdgcn ||344getTriple().getArch() == llvm::Triple::spirv64);345return new tools::AMDGCN::Linker(*this);346}347348void HIPAMDToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {349AMDGPUToolChain::addClangWarningOptions(CC1Args);350HostTC.addClangWarningOptions(CC1Args);351}352353ToolChain::CXXStdlibType354HIPAMDToolChain::GetCXXStdlibType(const ArgList &Args) const {355return HostTC.GetCXXStdlibType(Args);356}357358void HIPAMDToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,359ArgStringList &CC1Args) const {360HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);361}362363void HIPAMDToolChain::AddClangCXXStdlibIncludeArgs(364const ArgList &Args, ArgStringList &CC1Args) const {365HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);366}367368void HIPAMDToolChain::AddIAMCUIncludeArgs(const ArgList &Args,369ArgStringList &CC1Args) const {370HostTC.AddIAMCUIncludeArgs(Args, CC1Args);371}372373void HIPAMDToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,374ArgStringList &CC1Args) const {375RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);376}377378SanitizerMask HIPAMDToolChain::getSupportedSanitizers() const {379// The HIPAMDToolChain only supports sanitizers in the sense that it allows380// sanitizer arguments on the command line if they are supported by the host381// toolchain. The HIPAMDToolChain will actually ignore any command line382// arguments for any of these "supported" sanitizers. That means that no383// sanitization of device code is actually supported at this time.384//385// This behavior is necessary because the host and device toolchains386// invocations often share the command line, so the device toolchain must387// tolerate flags meant only for the host toolchain.388return HostTC.getSupportedSanitizers();389}390391VersionTuple HIPAMDToolChain::computeMSVCVersion(const Driver *D,392const ArgList &Args) const {393return HostTC.computeMSVCVersion(D, Args);394}395396llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12>397HIPAMDToolChain::getDeviceLibs(const llvm::opt::ArgList &DriverArgs) const {398llvm::SmallVector<BitCodeLibraryInfo, 12> BCLibs;399if (DriverArgs.hasArg(options::OPT_nogpulib) ||400(getTriple().getArch() == llvm::Triple::spirv64 &&401getTriple().getVendor() == llvm::Triple::AMD))402return {};403ArgStringList LibraryPaths;404405// Find in --hip-device-lib-path and HIP_LIBRARY_PATH.406for (StringRef Path : RocmInstallation->getRocmDeviceLibPathArg())407LibraryPaths.push_back(DriverArgs.MakeArgString(Path));408409addDirectoryList(DriverArgs, LibraryPaths, "", "HIP_DEVICE_LIB_PATH");410411// Maintain compatability with --hip-device-lib.412auto BCLibArgs = DriverArgs.getAllArgValues(options::OPT_hip_device_lib_EQ);413if (!BCLibArgs.empty()) {414llvm::for_each(BCLibArgs, [&](StringRef BCName) {415StringRef FullName;416for (StringRef LibraryPath : LibraryPaths) {417SmallString<128> Path(LibraryPath);418llvm::sys::path::append(Path, BCName);419FullName = Path;420if (llvm::sys::fs::exists(FullName)) {421BCLibs.push_back(FullName);422return;423}424}425getDriver().Diag(diag::err_drv_no_such_file) << BCName;426});427} else {428if (!RocmInstallation->hasDeviceLibrary()) {429getDriver().Diag(diag::err_drv_no_rocm_device_lib) << 0;430return {};431}432StringRef GpuArch = getGPUArch(DriverArgs);433assert(!GpuArch.empty() && "Must have an explicit GPU arch.");434435// If --hip-device-lib is not set, add the default bitcode libraries.436if (DriverArgs.hasFlag(options::OPT_fgpu_sanitize,437options::OPT_fno_gpu_sanitize, true) &&438getSanitizerArgs(DriverArgs).needsAsanRt()) {439auto AsanRTL = RocmInstallation->getAsanRTLPath();440if (AsanRTL.empty()) {441unsigned DiagID = getDriver().getDiags().getCustomDiagID(442DiagnosticsEngine::Error,443"AMDGPU address sanitizer runtime library (asanrtl) is not found. "444"Please install ROCm device library which supports address "445"sanitizer");446getDriver().Diag(DiagID);447return {};448} else449BCLibs.emplace_back(AsanRTL, /*ShouldInternalize=*/false);450}451452// Add the HIP specific bitcode library.453BCLibs.push_back(RocmInstallation->getHIPPath());454455// Add common device libraries like ocml etc.456for (StringRef N : getCommonDeviceLibNames(DriverArgs, GpuArch.str()))457BCLibs.emplace_back(N);458459// Add instrument lib.460auto InstLib =461DriverArgs.getLastArgValue(options::OPT_gpu_instrument_lib_EQ);462if (InstLib.empty())463return BCLibs;464if (llvm::sys::fs::exists(InstLib))465BCLibs.push_back(InstLib);466else467getDriver().Diag(diag::err_drv_no_such_file) << InstLib;468}469470return BCLibs;471}472473void HIPAMDToolChain::checkTargetID(474const llvm::opt::ArgList &DriverArgs) const {475auto PTID = getParsedTargetID(DriverArgs);476if (PTID.OptionalTargetID && !PTID.OptionalGPUArch) {477getDriver().Diag(clang::diag::err_drv_bad_target_id)478<< *PTID.OptionalTargetID;479}480}481482483