clang 23.0.0git
HIPSPV.cpp
Go to the documentation of this file.
1//===--- HIPSPV.cpp - HIPSPV ToolChain Implementation -----------*- 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 "HIPSPV.h"
10#include "HIPUtility.h"
13#include "clang/Driver/Driver.h"
16#include "llvm/Support/FileSystem.h"
17#include "llvm/Support/Path.h"
18
19using namespace clang::driver;
20using namespace clang::driver::toolchains;
21using namespace clang::driver::tools;
22using namespace clang;
23using namespace llvm::opt;
24
25// Locates HIP pass plugin.
26static std::string findPassPlugin(const Driver &D,
27 const llvm::opt::ArgList &Args) {
28 StringRef Path = Args.getLastArgValue(options::OPT_hipspv_pass_plugin_EQ);
29 if (!Path.empty()) {
30 if (llvm::sys::fs::exists(Path))
31 return Path.str();
32 D.Diag(diag::err_drv_no_such_file) << Path;
33 }
34
35 StringRef hipPath = Args.getLastArgValue(options::OPT_hip_path_EQ);
36 if (!hipPath.empty()) {
37 SmallString<128> PluginPath(hipPath);
38 llvm::sys::path::append(PluginPath, "lib", "libLLVMHipSpvPasses.so");
39 if (llvm::sys::fs::exists(PluginPath))
40 return PluginPath.str().str();
41 PluginPath.assign(hipPath);
42 llvm::sys::path::append(PluginPath, "lib", "llvm",
43 "libLLVMHipSpvPasses.so");
44 if (llvm::sys::fs::exists(PluginPath))
45 return PluginPath.str().str();
46 }
47
48 return std::string();
49}
50
51void HIPSPV::Linker::constructLinkAndEmitSpirvCommand(
52 Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
53 const InputInfo &Output, const llvm::opt::ArgList &Args) const {
54
55 assert(!Inputs.empty() && "Must have at least one input.");
56 std::string Name = std::string(llvm::sys::path::stem(Output.getFilename()));
57 const char *TempFile = HIP::getTempFile(C, Name + "-link", "bc");
58
59 // Link LLVM bitcode.
60 ArgStringList LinkArgs{};
61
62 for (auto Input : Inputs)
63 LinkArgs.push_back(Input.getFilename());
64
65 // Add static device libraries using the common helper function.
66 // This handles unbundling archives (.a) containing bitcode bundles.
67 StringRef Arch = getToolChain().getTriple().getArchName();
68 StringRef Target =
69 "generic"; // SPIR-V is generic, no specific target ID like -mcpu
70 tools::AddStaticDeviceLibsLinking(C, *this, JA, Inputs, Args, LinkArgs, Arch,
71 Target, /*IsBitCodeSDL=*/true);
72 tools::constructLLVMLinkCommand(C, *this, JA, Inputs, LinkArgs, Output, Args,
73 TempFile);
74
75 // Post-link HIP lowering.
76
77 // Run LLVM IR passes to lower/expand/emulate HIP code that does not translate
78 // to SPIR-V (E.g. dynamic shared memory).
79 auto PassPluginPath = findPassPlugin(C.getDriver(), Args);
80 if (!PassPluginPath.empty()) {
81 const char *PassPathCStr = C.getArgs().MakeArgString(PassPluginPath);
82 const char *OptOutput = HIP::getTempFile(C, Name + "-lower", "bc");
83 ArgStringList OptArgs{TempFile, "-load-pass-plugin",
84 PassPathCStr, "-passes=hip-post-link-passes",
85 "-o", OptOutput};
86 const char *Opt = Args.MakeArgString(getToolChain().GetProgramPath("opt"));
87 C.addCommand(std::make_unique<Command>(
88 JA, *this, ResponseFileSupport::None(), Opt, OptArgs, Inputs, Output));
89 TempFile = OptOutput;
90 }
91
92 // Emit SPIR-V binary.
93 llvm::opt::ArgStringList TrArgs;
94 auto T = getToolChain().getTriple();
95 bool HasNoSubArch = T.getSubArch() == llvm::Triple::NoSubArch;
96 if (T.getOS() == llvm::Triple::ChipStar) {
97 // chipStar needs 1.2 for supporting warp-level primitivies via sub-group
98 // extensions. Strictly put we'd need 1.3 for the standard non-extension
99 // shuffle operations, but it's not supported by any backend driver of the
100 // chipStar.
101 if (HasNoSubArch)
102 TrArgs.push_back("--spirv-max-version=1.2");
103 TrArgs.push_back("--spirv-ext=-all"
104 // Needed for experimental indirect call support.
105 ",+SPV_INTEL_function_pointers"
106 // Needed for shuffles below SPIR-V 1.3
107 ",+SPV_INTEL_subgroups");
108 } else {
109 if (HasNoSubArch)
110 TrArgs.push_back("--spirv-max-version=1.1");
111 TrArgs.push_back("--spirv-ext=+all");
112 }
113
114 InputInfo TrInput = InputInfo(types::TY_LLVM_BC, TempFile, "");
115 SPIRV::constructTranslateCommand(C, *this, JA, Output, TrInput, TrArgs);
116}
117
119 const InputInfo &Output,
120 const InputInfoList &Inputs,
121 const ArgList &Args,
122 const char *LinkingOutput) const {
123 if (Inputs.size() > 0 && Inputs[0].getType() == types::TY_Image &&
124 JA.getType() == types::TY_Object)
126 Args, JA, *this);
127
128 if (JA.getType() == types::TY_HIP_FATBIN)
129 return HIP::constructHIPFatbinCommand(C, JA, Output.getFilename(), Inputs,
130 Args, *this);
131
132 constructLinkAndEmitSpirvCommand(C, JA, Inputs, Output, Args);
133}
134
135HIPSPVToolChain::HIPSPVToolChain(const Driver &D, const llvm::Triple &Triple,
136 const ToolChain &HostTC, const ArgList &Args)
137 : ToolChain(D, Triple, Args), HostTC(&HostTC) {
138 // Lookup binaries into the driver directory, this is used to
139 // discover the clang-offload-bundler executable.
140 getProgramPaths().push_back(getDriver().Dir);
141}
142
143// Non-offloading toolchain. Primaly used by clang-offload-linker.
144HIPSPVToolChain::HIPSPVToolChain(const Driver &D, const llvm::Triple &Triple,
145 const ArgList &Args)
146 : ToolChain(D, Triple, Args), HostTC(nullptr) {
147 // Lookup binaries into the driver directory, this is used to
148 // discover the clang-offload-bundler executable.
149 getProgramPaths().push_back(getDriver().Dir);
150}
151
153 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
154 Action::OffloadKind DeviceOffloadingKind) const {
155
156 if (!HostTC) {
157 assert(DeviceOffloadingKind == Action::OFK_None &&
158 "Need host toolchain for offloading!");
159 return;
160 }
161
162 HostTC->addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
163
164 assert(DeviceOffloadingKind == Action::OFK_HIP &&
165 "Only HIP offloading kinds are supported for GPUs.");
166
167 CC1Args.append(
168 {"-fcuda-is-device",
169 // A crude workaround for llvm-spirv which does not handle the
170 // autovectorized code well (vector reductions, non-i{8,16,32,64} types).
171 // TODO: Allow autovectorization when SPIR-V backend arrives.
172 "-mllvm", "-vectorize-loops=false", "-mllvm", "-vectorize-slp=false"});
173
174 // Default to "hidden" visibility, as object level linking will not be
175 // supported for the foreseeable future.
176 if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
177 options::OPT_fvisibility_ms_compat))
178 CC1Args.append(
179 {"-fvisibility=hidden", "-fapply-global-visibility-to-externs"});
180
181 for (const BitCodeLibraryInfo &BCFile :
182 getDeviceLibs(DriverArgs, DeviceOffloadingKind))
183 CC1Args.append(
184 {"-mlink-builtin-bitcode", DriverArgs.MakeArgString(BCFile.Path)});
185}
186
188 assert(getTriple().getArch() == llvm::Triple::spirv64);
189 return new tools::HIPSPV::Linker(*this);
190}
191
192void HIPSPVToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
193 if (HostTC)
194 HostTC->addClangWarningOptions(CC1Args);
196}
197
199HIPSPVToolChain::GetCXXStdlibType(const ArgList &Args) const {
200 if (HostTC)
201 return HostTC->GetCXXStdlibType(Args);
202 return ToolChain::GetCXXStdlibType(Args);
203}
204
205void HIPSPVToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
206 ArgStringList &CC1Args) const {
207 if (HostTC)
208 HostTC->AddClangSystemIncludeArgs(DriverArgs, CC1Args);
209 ToolChain::AddClangSystemIncludeArgs(DriverArgs, CC1Args);
210}
211
213 const ArgList &Args, ArgStringList &CC1Args) const {
214 if (HostTC)
215 HostTC->AddClangCXXStdlibIncludeArgs(Args, CC1Args);
217}
218
220 ArgStringList &CC1Args) const {
221 if (HostTC)
222 HostTC->AddIAMCUIncludeArgs(Args, CC1Args);
223 ToolChain::AddIAMCUIncludeArgs(Args, CC1Args);
224}
225
226void HIPSPVToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
227 ArgStringList &CC1Args) const {
228 if (!DriverArgs.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
229 true))
230 return;
231
232 StringRef hipPath = DriverArgs.getLastArgValue(options::OPT_hip_path_EQ);
233 if (hipPath.empty()) {
234 getDriver().Diag(diag::err_drv_hipspv_no_hip_path);
235 return;
236 }
237 SmallString<128> P(hipPath);
238 llvm::sys::path::append(P, "include");
239 CC1Args.append({"-isystem", DriverArgs.MakeArgString(P)});
240}
241
244 const llvm::opt::ArgList &DriverArgs,
245 const Action::OffloadKind DeviceOffloadingKind) const {
247 if (!DriverArgs.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib,
248 true))
249 return {};
250
251 ArgStringList LibraryPaths;
252 // Find device libraries in --hip-device-lib-path and HIP_DEVICE_LIB_PATH.
253 auto HipDeviceLibPathArgs = DriverArgs.getAllArgValues(
254 // --hip-device-lib-path is alias to this option.
255 options::OPT_rocm_device_lib_path_EQ);
256 for (auto Path : HipDeviceLibPathArgs)
257 LibraryPaths.push_back(DriverArgs.MakeArgString(Path));
258
259 StringRef HipPath = DriverArgs.getLastArgValue(options::OPT_hip_path_EQ);
260 if (!HipPath.empty()) {
261 SmallString<128> Path(HipPath);
262 llvm::sys::path::append(Path, "lib", "hip-device-lib");
263 LibraryPaths.push_back(DriverArgs.MakeArgString(Path));
264 }
265
266 addDirectoryList(DriverArgs, LibraryPaths, "", "HIP_DEVICE_LIB_PATH");
267
268 // Maintain compatability with --hip-device-lib.
269 auto BCLibArgs = DriverArgs.getAllArgValues(options::OPT_hip_device_lib_EQ);
270 if (!BCLibArgs.empty()) {
271 bool Found = false;
272 for (StringRef BCName : BCLibArgs) {
273 StringRef FullName;
274 for (std::string LibraryPath : LibraryPaths) {
275 SmallString<128> Path(LibraryPath);
276 llvm::sys::path::append(Path, BCName);
277 FullName = Path;
278 if (llvm::sys::fs::exists(FullName)) {
279 BCLibs.emplace_back(FullName.str());
280 Found = true;
281 break;
282 }
283 }
284 if (!Found)
285 getDriver().Diag(diag::err_drv_no_such_file) << BCName;
286 }
287 } else {
288 // Search device library named as 'hipspv-<triple>.bc'.
289 auto TT = getTriple().normalize();
290 std::string BCName = "hipspv-" + TT + ".bc";
291 for (auto *LibPath : LibraryPaths) {
292 SmallString<128> Path(LibPath);
293 llvm::sys::path::append(Path, BCName);
294 if (llvm::sys::fs::exists(Path)) {
295 BCLibs.emplace_back(Path.str().str());
296 return BCLibs;
297 }
298 }
299 getDriver().Diag(diag::err_drv_no_hipspv_device_lib)
300 << 1 << ("'" + TT + "' target");
301 return {};
302 }
303
304 return BCLibs;
305}
306
308 // The HIPSPVToolChain only supports sanitizers in the sense that it allows
309 // sanitizer arguments on the command line if they are supported by the host
310 // toolchain. The HIPSPVToolChain will actually ignore any command line
311 // arguments for any of these "supported" sanitizers. That means that no
312 // sanitization of device code is actually supported at this time.
313 //
314 // This behavior is necessary because the host and device toolchains
315 // invocations often share the command line, so the device toolchain must
316 // tolerate flags meant only for the host toolchain.
317 if (HostTC)
318 return HostTC->getSupportedSanitizers();
320}
321
323 const ArgList &Args) const {
324 if (HostTC)
325 return HostTC->computeMSVCVersion(D, Args);
326 return ToolChain::computeMSVCVersion(D, Args);
327}
328
330 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
331 const llvm::opt::ArgList &Args) const {
332 // Debug info generation is disabled for SPIRV-LLVM-Translator
333 // which currently aborts on the presence of DW_OP_LLVM_convert.
334 // TODO: Enable debug info when the SPIR-V backend arrives.
335 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
336}
static std::string findPassPlugin(const Driver &D, const llvm::opt::ArgList &Args)
Definition HIPSPV.cpp:26
types::ID getType() const
Definition Action.h:150
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:99
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:169
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getFilename() const
Definition InputInfo.h:83
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:92
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:277
const Driver & getDriver() const
Definition ToolChain.h:261
const llvm::Triple & getTriple() const
Definition ToolChain.h:263
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
virtual void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add the clang cc1 arguments for system include paths.
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Tool - Information on a specific compilation tool.
Definition Tool.h:32
const ToolChain & getToolChain() const
Definition Tool.h:52
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition HIPSPV.cpp:152
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Definition HIPSPV.cpp:205
void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override
Add warning options that need to be passed to cc1 for this target.
Definition HIPSPV.cpp:192
Tool * buildLinker() const override
Definition HIPSPV.cpp:187
llvm::SmallVector< BitCodeLibraryInfo, 12 > getDeviceLibs(const llvm::opt::ArgList &Args, const Action::OffloadKind DeviceOffloadKind) const override
Get paths for device libraries.
Definition HIPSPV.cpp:243
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific HIP includes.
Definition HIPSPV.cpp:226
HIPSPVToolChain(const Driver &D, const llvm::Triple &Triple, const ToolChain &HostTC, const llvm::opt::ArgList &Args)
CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override
Definition HIPSPV.cpp:199
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition HIPSPV.cpp:212
VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const override
On Windows, returns the MSVC compatibility version.
Definition HIPSPV.cpp:322
void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use MCU GCC toolchain includes.
Definition HIPSPV.cpp:219
void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const override
Adjust debug information kind considering all passed options.
Definition HIPSPV.cpp:329
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
Definition HIPSPV.cpp:307
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition HIPSPV.cpp:118
void constructHIPFatbinCommand(Compilation &C, const JobAction &JA, StringRef OutputFileName, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const Tool &T)
const char * getTempFile(Compilation &C, StringRef Prefix, StringRef Extension)
void constructGenerateObjFileFromHIPFatBinary(Compilation &C, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, const JobAction &JA, const Tool &T)
void constructTranslateCommand(Compilation &C, const Tool &T, const JobAction &JA, const InputInfo &Output, const InputInfo &Input, const llvm::opt::ArgStringList &Args)
Definition SPIRV.cpp:20
void AddStaticDeviceLibsLinking(Compilation &C, const Tool &T, const JobAction &JA, const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CmdArgs, StringRef Arch, StringRef Target, bool isBitCodeSDL)
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
EnvVar is split by system delimiter for environment variables.
void constructLLVMLinkCommand(Compilation &C, const Tool &T, const JobAction &JA, const InputInfoList &JobInputs, const llvm::opt::ArgStringList &LinkerInputs, const InputInfo &Output, const llvm::opt::ArgList &Args, const char *OutputFilename=nullptr)
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:50
The JSON file list parser is used to communicate input to InstallAPI.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition Job.h:78