Debian Codegraph @

third_party/rust/wgpu-hal/src/dx12/shader_compilation.rs

raw
1 use alloc::{string::String, vec::Vec};
2 use core::ffi::CStr;
3 use std::path::PathBuf;
4
5 use crate::auxil::dxgi::result::HResult;
6 use thiserror::Error;
7 use windows::{
8 core::{Interface, PCSTR, PCWSTR},
9 Win32::Graphics::Direct3D::{Dxc, Fxc},
10 };
11
12 pub(super) fn compile_fxc(
13 device: &super::Device,
14 source: &str,
15 source_name: Option<&CStr>,
16 raw_ep: &str,
17 stage_bit: wgt::ShaderStages,
18 full_stage: &str,
19 ) -> Result<super::CompiledShader, crate::PipelineError> {
20 profiling::scope!("compile_fxc");
21 let mut shader_data = None;
22 let mut compile_flags = Fxc::D3DCOMPILE_ENABLE_STRICTNESS;
23 if device
24 .shared
25 .private_caps
26 .instance_flags
27 .contains(wgt::InstanceFlags::DEBUG)
28 {
29 compile_flags |= Fxc::D3DCOMPILE_DEBUG | Fxc::D3DCOMPILE_SKIP_OPTIMIZATION;
30 }
31
32 let raw_ep = alloc::ffi::CString::new(raw_ep).unwrap();
33 let full_stage = alloc::ffi::CString::new(full_stage).unwrap();
34
35 // If no name has been set, D3DCompile wants the null pointer.
36 let source_name = source_name
37 .map(|cstr| cstr.as_ptr().cast())
38 .unwrap_or(core::ptr::null());
39
40 let mut error = None;
41 let hr = unsafe {
42 profiling::scope!("Fxc::D3DCompile");
43 Fxc::D3DCompile(
44 // TODO: Update low-level bindings to accept a slice here
45 source.as_ptr().cast(),
46 source.len(),
47 PCSTR(source_name),
48 None,
49 None,
50 PCSTR(raw_ep.as_ptr().cast()),
51 PCSTR(full_stage.as_ptr().cast()),
52 compile_flags,
53 0,
54 &mut shader_data,
55 Some(&mut error),
56 )
57 };
58
59 match hr {
60 Ok(()) => {
61 let shader_data = shader_data.unwrap();
62 Ok(super::CompiledShader::Fxc(shader_data))
63 }
64 Err(e) => {
65 let mut full_msg = format!("FXC D3DCompile error ({e})");
66 if let Some(error) = error {
67 use core::fmt::Write as _;
68 let message = unsafe {
69 core::slice::from_raw_parts(
70 error.GetBufferPointer().cast(),
71 error.GetBufferSize(),
72 )
73 };
74 let _ = write!(full_msg, ": {}", String::from_utf8_lossy(message));
75 }
76 Err(crate::PipelineError::Linkage(stage_bit, full_msg))
77 }
78 }
79 }
80
81 trait DxcObj: Interface {
82 const CLSID: windows::core::GUID;
83 }
84 impl DxcObj for Dxc::IDxcCompiler3 {
85 const CLSID: windows::core::GUID = Dxc::CLSID_DxcCompiler;
86 }
87 impl DxcObj for Dxc::IDxcUtils {
88 const CLSID: windows::core::GUID = Dxc::CLSID_DxcUtils;
89 }
90 impl DxcObj for Dxc::IDxcValidator {
91 const CLSID: windows::core::GUID = Dxc::CLSID_DxcValidator;
92 }
93
94 #[derive(Debug)]
95 struct DxcLib {
96 lib: crate::dx12::DynLib,
97 }
98
99 impl DxcLib {
100 fn new_dynamic(lib_path: PathBuf) -> Result<Self, libloading::Error> {
101 unsafe { crate::dx12::DynLib::new(lib_path).map(|lib| Self { lib }) }
102 }
103
104 pub fn create_instance<T: DxcObj>(&self) -> Result<T, crate::DeviceError> {
105 unsafe {
106 type DxcCreateInstanceFn = unsafe extern "system" fn(
107 rclsid: *const windows_core::GUID,
108 riid: *const windows_core::GUID,
109 ppv: *mut *mut core::ffi::c_void,
110 )
111 -> windows_core::HRESULT;
112
113 let func: libloading::Symbol<DxcCreateInstanceFn> =
114 self.lib.get(c"DxcCreateInstance".to_bytes())?;
115 dxc_create_instance::<T>(|clsid, iid, ppv| func(clsid, iid, ppv))
116 }
117 }
118 }
119
120 /// Invokes the provided library function to create a DXC object.
121 unsafe fn dxc_create_instance<T: DxcObj>(
122 f: impl Fn(
123 *const windows_core::GUID,
124 *const windows_core::GUID,
125 *mut *mut core::ffi::c_void,
126 ) -> windows_core::HRESULT,
127 ) -> Result<T, crate::DeviceError> {
128 let mut result__ = None;
129 f(&T::CLSID, &T::IID, <*mut _>::cast(&mut result__))
130 .ok()
131 .into_device_result("DxcCreateInstance")?;
132 result__.ok_or(crate::DeviceError::Unexpected)
133 }
134
135 pub(super) struct DxcContainer {
136 pub(super) max_shader_model: wgt::DxcShaderModel,
137 compiler: Dxc::IDxcCompiler3,
138 // Has to be held onto for the lifetime of the device otherwise shaders will fail to compile.
139 // Only needed when using dynamic linking.
140 _dxc: Option<DxcLib>,
141 }
142
143 #[derive(Debug, Error)]
144 pub(super) enum GetDynamicDXCContainerError {
145 #[error(transparent)]
146 Device(#[from] crate::DeviceError),
147 #[error("Failed to load {0}: {1}")]
148 FailedToLoad(&'static str, libloading::Error),
149 }
150
151 pub(super) fn get_dynamic_dxc_container(
152 dxc_path: PathBuf,
153 max_shader_model: wgt::DxcShaderModel,
154 ) -> Result<DxcContainer, GetDynamicDXCContainerError> {
155 let dxc = DxcLib::new_dynamic(dxc_path)
156 .map_err(|e| GetDynamicDXCContainerError::FailedToLoad("dxcompiler.dll", e))?;
157
158 let compiler = dxc.create_instance::<Dxc::IDxcCompiler3>()?;
159
160 Ok(DxcContainer {
161 max_shader_model,
162 compiler,
163 _dxc: Some(dxc),
164 })
165 }
166
167 /// Creates a [`DxcContainer`] that delegates to the statically-linked version of DXC.
168 pub(super) fn get_static_dxc_container() -> Result<DxcContainer, crate::DeviceError> {
169 #[cfg(static_dxc)]
170 {
171 unsafe {
172 let compiler = dxc_create_instance::<Dxc::IDxcCompiler3>(|clsid, iid, ppv| {
173 windows_core::HRESULT(mach_dxcompiler_rs::DxcCreateInstance(
174 clsid.cast(),
175 iid.cast(),
176 ppv,
177 ))
178 })?;
179
180 Ok(DxcContainer {
181 max_shader_model: wgt::DxcShaderModel::V6_7,
182 compiler,
183 _dxc: None,
184 })
185 }
186 }
187 #[cfg(not(static_dxc))]
188 {
189 panic!("Attempted to create a static DXC shader compiler, but the static-dxc feature was not enabled")
190 }
191 }
192
193 /// Owned PCWSTR
194 #[allow(clippy::upper_case_acronyms)]
195 struct OPCWSTR {
196 inner: Vec<u16>,
197 }
198
199 impl OPCWSTR {
200 fn new(s: &str) -> Self {
201 let mut inner: Vec<_> = s.encode_utf16().collect();
202 inner.push(0);
203 Self { inner }
204 }
205
206 fn ptr(&self) -> PCWSTR {
207 PCWSTR(self.inner.as_ptr())
208 }
209 }
210
211 fn get_output<T: Interface>(
212 res: &Dxc::IDxcResult,
213 kind: Dxc::DXC_OUT_KIND,
214 ) -> Result<T, crate::DeviceError> {
215 let mut result__: Option<T> = None;
216 unsafe { res.GetOutput::<T>(kind, &mut None, <*mut _>::cast(&mut result__)) }
217 .into_device_result("GetOutput")?;
218 result__.ok_or(crate::DeviceError::Unexpected)
219 }
220
221 fn as_err_str(blob: &Dxc::IDxcBlobUtf8) -> Result<&str, crate::DeviceError> {
222 let ptr = unsafe { blob.GetStringPointer() };
223 let len = unsafe { blob.GetStringLength() };
224 core::str::from_utf8(unsafe { core::slice::from_raw_parts(ptr.0, len) })
225 .map_err(|_| crate::DeviceError::Unexpected)
226 }
227
228 pub(super) fn compile_dxc(
229 device: &crate::dx12::Device,
230 source: &str,
231 source_name: Option<&CStr>,
232 raw_ep: &str,
233 stage_bit: wgt::ShaderStages,
234 full_stage: &str,
235 dxc_container: &DxcContainer,
236 ) -> Result<crate::dx12::CompiledShader, crate::PipelineError> {
237 profiling::scope!("compile_dxc");
238
239 let source_name = source_name.and_then(|cstr| cstr.to_str().ok());
240
241 let source_name = source_name.map(OPCWSTR::new);
242 let raw_ep = OPCWSTR::new(raw_ep);
243 let full_stage = OPCWSTR::new(full_stage);
244
245 let mut compile_args = arrayvec::ArrayVec::<PCWSTR, 13>::new_const();
246
247 if let Some(source_name) = source_name.as_ref() {
248 compile_args.push(source_name.ptr())
249 }
250
251 compile_args.extend([
252 windows::core::w!("-E"),
253 raw_ep.ptr(),
254 windows::core::w!("-T"),
255 full_stage.ptr(),
256 windows::core::w!("-HV"),
257 windows::core::w!("2018"), // Use HLSL 2018, Naga doesn't supported 2021 yet.
258 windows::core::w!("-no-warnings"),
259 Dxc::DXC_ARG_ENABLE_STRICTNESS,
260 ]);
261
262 if device
263 .shared
264 .private_caps
265 .instance_flags
266 .contains(wgt::InstanceFlags::DEBUG)
267 {
268 compile_args.push(Dxc::DXC_ARG_DEBUG);
269 compile_args.push(Dxc::DXC_ARG_SKIP_OPTIMIZATIONS);
270 }
271
272 if device.features.contains(wgt::Features::SHADER_F16) {
273 compile_args.push(windows::core::w!("-enable-16bit-types"));
274 }
275
276 let buffer = Dxc::DxcBuffer {
277 Ptr: source.as_ptr().cast(),
278 Size: source.len(),
279 Encoding: Dxc::DXC_CP_UTF8.0,
280 };
281
282 let compile_res: Dxc::IDxcResult = unsafe {
283 dxc_container
284 .compiler
285 .Compile(&buffer, Some(&compile_args), None)
286 }
287 .into_device_result("Compile")?;
288
289 drop(compile_args);
290 drop(source_name);
291 drop(raw_ep);
292 drop(full_stage);
293
294 let err_blob = get_output::<Dxc::IDxcBlobUtf8>(&compile_res, Dxc::DXC_OUT_ERRORS)?;
295
296 let len = unsafe { err_blob.GetStringLength() };
297 if len != 0 {
298 let err = as_err_str(&err_blob)?;
299 return Err(crate::PipelineError::Linkage(
300 stage_bit,
301 format!("DXC compile error: {err}"),
302 ));
303 }
304
305 let blob = get_output::<Dxc::IDxcBlob>(&compile_res, Dxc::DXC_OUT_OBJECT)?;
306
307 Ok(crate::dx12::CompiledShader::Dxc(blob))
308 }