1use crate::maybe_pqp_cg_ssa as rustc_codegen_ssa;
3
4use super::CodegenCx;
5use crate::abi::ConvSpirvType;
6use crate::builder_spirv::{SpirvConst, SpirvValue, SpirvValueExt, SpirvValueKind};
7use crate::spirv_type::SpirvType;
8use itertools::Itertools as _;
9use rspirv::spirv::Word;
10use rustc_abi::{self as abi, AddressSpace, Float, HasDataLayout, Integer, Primitive, Size};
11use rustc_codegen_ssa::traits::{ConstCodegenMethods, MiscCodegenMethods, StaticCodegenMethods};
12use rustc_middle::mir::interpret::{AllocError, ConstAllocation, GlobalAlloc, Scalar, alloc_range};
13use rustc_middle::ty::layout::LayoutOf;
14use rustc_session::PointerAuthSchema;
15use rustc_span::{DUMMY_SP, Span};
16
17impl<'tcx> CodegenCx<'tcx> {
18 pub fn def_constant(&self, ty: Word, val: SpirvConst<'_, 'tcx>) -> SpirvValue {
19 self.builder.def_constant_cx(ty, val, self)
20 }
21
22 pub fn constant_u8(&self, span: Span, val: u8) -> SpirvValue {
23 self.constant_int_from_native_unsigned(span, val)
24 }
25
26 pub fn constant_i8(&self, span: Span, val: i8) -> SpirvValue {
27 self.constant_int_from_native_signed(span, val)
28 }
29
30 pub fn constant_i16(&self, span: Span, val: i16) -> SpirvValue {
31 self.constant_int_from_native_signed(span, val)
32 }
33
34 pub fn constant_u16(&self, span: Span, val: u16) -> SpirvValue {
35 self.constant_int_from_native_unsigned(span, val)
36 }
37
38 pub fn constant_i32(&self, span: Span, val: i32) -> SpirvValue {
39 self.constant_int_from_native_signed(span, val)
40 }
41
42 pub fn constant_u32(&self, span: Span, val: u32) -> SpirvValue {
43 self.constant_int_from_native_unsigned(span, val)
44 }
45
46 pub fn constant_i64(&self, span: Span, val: i64) -> SpirvValue {
47 self.constant_int_from_native_signed(span, val)
48 }
49
50 pub fn constant_u64(&self, span: Span, val: u64) -> SpirvValue {
51 self.constant_int_from_native_unsigned(span, val)
52 }
53
54 pub fn constant_u128(&self, span: Span, val: u128) -> SpirvValue {
55 self.constant_int_from_native_unsigned(span, val)
56 }
57
58 fn constant_int_from_native_unsigned(&self, span: Span, val: impl Into<u128>) -> SpirvValue {
59 let size = Size::from_bytes(std::mem::size_of_val(&val));
60 let ty = SpirvType::Integer(size.bits() as u32, false).def(span, self);
61 self.constant_int(ty, val.into())
62 }
63
64 fn constant_int_from_native_signed(&self, span: Span, val: impl Into<i128>) -> SpirvValue {
65 let size = Size::from_bytes(std::mem::size_of_val(&val));
66 let ty = SpirvType::Integer(size.bits() as u32, true).def(span, self);
67 self.constant_int(ty, val.into() as u128)
68 }
69
70 pub fn constant_int(&self, ty: Word, val: u128) -> SpirvValue {
71 self.def_constant(ty, SpirvConst::Scalar(val))
72 }
73
74 pub fn constant_f32(&self, span: Span, val: f32) -> SpirvValue {
75 let ty = SpirvType::Float(32).def(span, self);
76 self.def_constant(ty, SpirvConst::Scalar(val.to_bits().into()))
77 }
78
79 pub fn constant_f64(&self, span: Span, val: f64) -> SpirvValue {
80 let ty = SpirvType::Float(64).def(span, self);
81 self.def_constant(ty, SpirvConst::Scalar(val.to_bits().into()))
82 }
83
84 pub fn constant_float(&self, ty: Word, val: f64) -> SpirvValue {
85 match self.lookup_type(ty) {
86 SpirvType::Float(32) => {
88 self.def_constant(ty, SpirvConst::Scalar((val as f32).to_bits().into()))
89 }
90 SpirvType::Float(64) => self.def_constant(ty, SpirvConst::Scalar(val.to_bits().into())),
91 other => self.tcx.dcx().fatal(format!(
92 "constant_float does not support type {}",
93 other.debug(ty, self)
94 )),
95 }
96 }
97
98 pub fn constant_bool(&self, span: Span, val: bool) -> SpirvValue {
99 let ty = SpirvType::Bool.def(span, self);
100 self.def_constant(ty, SpirvConst::Scalar(val as u128))
101 }
102
103 pub fn constant_composite(&self, ty: Word, fields: impl Iterator<Item = Word>) -> SpirvValue {
104 self.def_constant(ty, SpirvConst::Composite(&fields.collect::<Vec<_>>()))
106 }
107
108 pub fn constant_null(&self, ty: Word) -> SpirvValue {
109 self.def_constant(ty, SpirvConst::Null)
110 }
111
112 pub fn undef(&self, ty: Word) -> SpirvValue {
113 self.def_constant(ty, SpirvConst::Undef)
114 }
115}
116
117impl ConstCodegenMethods for CodegenCx<'_> {
118 fn const_null(&self, t: Self::Type) -> Self::Value {
119 self.constant_null(t)
120 }
121 fn const_undef(&self, ty: Self::Type) -> Self::Value {
122 self.undef(ty)
123 }
124 fn const_poison(&self, ty: Self::Type) -> Self::Value {
125 self.const_undef(ty)
127 }
128 fn const_int(&self, t: Self::Type, i: i64) -> Self::Value {
129 self.constant_int(t, i as u128)
130 }
131 fn const_uint(&self, t: Self::Type, i: u64) -> Self::Value {
132 self.constant_int(t, i.into())
133 }
134 fn const_uint_big(&self, t: Self::Type, i: u128) -> Self::Value {
135 self.constant_int(t, i)
136 }
137 fn const_bool(&self, val: bool) -> Self::Value {
138 self.constant_bool(DUMMY_SP, val)
139 }
140 fn const_i8(&self, i: i8) -> Self::Value {
141 self.constant_i8(DUMMY_SP, i)
142 }
143 fn const_i16(&self, i: i16) -> Self::Value {
144 self.constant_i16(DUMMY_SP, i)
145 }
146 fn const_i32(&self, i: i32) -> Self::Value {
147 self.constant_i32(DUMMY_SP, i)
148 }
149 fn const_i64(&self, i: i64) -> Self::Value {
150 self.constant_i64(DUMMY_SP, i)
151 }
152 fn const_u8(&self, i: u8) -> Self::Value {
153 self.constant_u8(DUMMY_SP, i)
154 }
155 fn const_u32(&self, i: u32) -> Self::Value {
156 self.constant_u32(DUMMY_SP, i)
157 }
158 fn const_u64(&self, i: u64) -> Self::Value {
159 self.constant_u64(DUMMY_SP, i)
160 }
161 fn const_u128(&self, i: u128) -> Self::Value {
162 let ty = SpirvType::Integer(128, false).def(DUMMY_SP, self);
163 self.const_uint_big(ty, i)
164 }
165 fn const_usize(&self, i: u64) -> Self::Value {
166 let ptr_size = self.tcx.data_layout.pointer_size().bits() as u32;
167 let t = SpirvType::Integer(ptr_size, false).def(DUMMY_SP, self);
168 self.constant_int(t, i.into())
169 }
170 fn const_real(&self, t: Self::Type, val: f64) -> Self::Value {
171 self.constant_float(t, val)
172 }
173
174 fn const_str(&self, s: &str) -> (Self::Value, Self::Value) {
175 let len = s.len();
176 let str_ty = self
177 .layout_of(self.tcx.types.str_)
178 .spirv_type(DUMMY_SP, self);
179 (
180 self.def_constant(
181 self.type_ptr_to(str_ty),
182 SpirvConst::PtrTo {
183 pointee: self
184 .constant_composite(
185 str_ty,
186 s.bytes().map(|b| self.const_u8(b).def_cx(self)),
187 )
188 .def_cx(self),
189 },
190 ),
191 self.const_usize(len as u64),
192 )
193 }
194 fn const_struct(&self, elts: &[Self::Value], _packed: bool) -> Self::Value {
195 let field_types = elts.iter().map(|f| f.ty).collect::<Vec<_>>();
198 let (field_offsets, size, align) = crate::abi::auto_struct_layout(self, &field_types);
199 let struct_ty = SpirvType::Adt {
200 def_id: None,
201 size,
202 align,
203 field_types: &field_types,
204 field_offsets: &field_offsets,
205 field_names: None,
206 }
207 .def(DUMMY_SP, self);
208 self.constant_composite(struct_ty, elts.iter().map(|f| f.def_cx(self)))
209 }
210 fn const_vector(&self, elts: &[Self::Value]) -> Self::Value {
211 let vector_ty = SpirvType::simd_vector(
212 self,
213 DUMMY_SP,
214 self.lookup_type(elts[0].ty),
215 elts.len() as u32,
216 )
217 .def(DUMMY_SP, self);
218 self.constant_composite(vector_ty, elts.iter().map(|elt| elt.def_cx(self)))
219 }
220
221 fn const_to_opt_uint(&self, v: Self::Value) -> Option<u64> {
222 self.builder.lookup_const_scalar(v)?.try_into().ok()
223 }
224 fn const_to_opt_u128(&self, v: Self::Value, _sign_ext: bool) -> Option<u128> {
227 self.builder.lookup_const_scalar(v)
228 }
229
230 fn scalar_to_backend_with_pac(
231 &self,
232 cv: Scalar,
233 layout: rustc_abi::Scalar,
234 ty: Self::Type,
235 _pac: Option<&PointerAuthSchema>,
236 ) -> Self::Value {
237 self.scalar_to_backend(cv, layout, ty)
238 }
239
240 fn scalar_to_backend(
241 &self,
242 scalar: Scalar,
243 layout: abi::Scalar,
244 ty: Self::Type,
245 ) -> Self::Value {
246 match scalar {
247 Scalar::Int(int) => {
248 assert_eq!(int.size(), layout.primitive().size(self));
249 let data = int.to_uint(int.size());
250
251 if let Primitive::Pointer(_) = layout.primitive() {
252 if data == 0 {
253 self.constant_null(ty)
254 } else {
255 let result = self.undef(ty);
256 self.zombie_no_span(
257 result.def_cx(self),
258 "pointer has non-null integer address",
259 );
260 result
261 }
262 } else {
263 self.def_constant(ty, SpirvConst::Scalar(data))
264 }
265 }
266 Scalar::Ptr(ptr, _) => {
267 let (prov, offset) = ptr.prov_and_relative_offset();
268 let alloc_id = prov.alloc_id();
269 let (base_addr, _base_addr_space) = match self.tcx.global_alloc(alloc_id) {
270 GlobalAlloc::Memory(alloc) => {
271 match self.lookup_type(ty) {
272 SpirvType::Pointer { .. } => {}
273 other => self.tcx.dcx().fatal(format!(
274 "GlobalAlloc::Memory type not implemented: {}",
275 other.debug(ty, self)
276 )),
277 }
278 let value = self.static_addr_of(alloc, None);
279 (value, AddressSpace::ZERO)
280 }
281 GlobalAlloc::Function { instance } => (
282 self.get_fn_addr(instance, None),
283 self.data_layout().instruction_address_space,
284 ),
285 GlobalAlloc::VTable(vty, dyn_ty) => {
286 let alloc = self
287 .tcx
288 .global_alloc(self.tcx.vtable_allocation((
289 vty,
290 dyn_ty.principal().map(|principal| {
291 self.tcx.instantiate_bound_regions_with_erased(principal)
292 }),
293 )))
294 .unwrap_memory();
295 match self.lookup_type(ty) {
296 SpirvType::Pointer { .. } => {}
297 other => self.tcx.dcx().fatal(format!(
298 "GlobalAlloc::VTable type not implemented: {}",
299 other.debug(ty, self)
300 )),
301 }
302 let value = self.static_addr_of(alloc, None);
303 (value, AddressSpace::ZERO)
304 }
305 GlobalAlloc::Static(def_id) => {
306 assert!(self.tcx.is_static(def_id));
307 assert!(!self.tcx.is_thread_local_static(def_id));
308 (self.get_static(def_id), AddressSpace::ZERO)
309 }
310 GlobalAlloc::TypeId { .. } => {
311 return if offset.bytes() == 0 {
312 self.constant_null(ty)
313 } else {
314 let result = self.undef(ty);
315 self.zombie_no_span(
316 result.def_cx(self),
317 "pointer has non-null integer address",
318 );
319 result
320 };
321 }
322 };
323 self.const_bitcast(self.const_ptr_byte_offset(base_addr, offset), ty)
324 }
325 }
326 }
327
328 fn const_ptr_byte_offset(&self, val: Self::Value, offset: Size) -> Self::Value {
329 if offset == Size::ZERO {
330 val
331 } else {
332 let result = val;
335 self.zombie_no_span(result.def_cx(self), "const_ptr_byte_offset");
336 result
337 }
338 }
339}
340
341impl<'tcx> CodegenCx<'tcx> {
342 pub(crate) fn const_data_from_alloc(&self, alloc: ConstAllocation<'_>) -> SpirvValue {
347 let alloc = self.tcx.lift(alloc);
351
352 let void_type = SpirvType::Void.def(DUMMY_SP, self);
353 self.def_constant(void_type, SpirvConst::ConstDataFromAlloc(alloc))
354 }
355
356 pub fn const_bitcast(&self, val: SpirvValue, ty: Word) -> SpirvValue {
357 if let SpirvValueKind::IllegalConst(_) = val.kind
360 && let Some(SpirvConst::PtrTo { pointee }) = self.builder.lookup_const(val)
361 && let Some(SpirvConst::ConstDataFromAlloc(alloc)) =
362 self.builder.lookup_const_by_id(pointee)
363 && let SpirvType::Pointer { pointee } = self.lookup_type(ty)
364 && let Some(init) = self.try_read_from_const_alloc(alloc, pointee)
365 {
366 return self.def_constant(
367 ty,
368 SpirvConst::PtrTo {
369 pointee: init.def_cx(self),
370 },
371 );
372 }
373
374 if val.ty == ty {
375 val
376 } else {
377 let result = val.def_cx(self).with_type(ty);
380 self.zombie_no_span(result.def_cx(self), "const_bitcast");
381 result
382 }
383 }
384
385 pub fn primitive_to_scalar(&self, value: Primitive) -> abi::Scalar {
388 let bits = value.size(self.data_layout()).bits();
389 assert!(bits <= 128);
390 abi::Scalar::Initialized {
391 value,
392 valid_range: abi::WrappingRange {
393 start: 0,
394 end: (!0 >> (128 - bits)),
395 },
396 }
397 }
398
399 pub fn try_read_from_const_alloc(
404 &self,
405 alloc: ConstAllocation<'tcx>,
406 ty: Word,
407 ) -> Option<SpirvValue> {
408 let (result, read_size) = self.read_from_const_alloc_at(alloc, ty, Size::ZERO);
409 (read_size == alloc.inner().size()).then_some(result)
410 }
411
412 #[tracing::instrument(level = "trace", skip(self), fields(ty = ?self.debug_type(ty), offset))]
417 fn read_from_const_alloc_at(
418 &self,
419 alloc: ConstAllocation<'tcx>,
420 ty: Word,
421 offset: Size,
422 ) -> (SpirvValue, Size) {
423 let ty_def = self.lookup_type(ty);
424 match ty_def {
425 SpirvType::Bool
426 | SpirvType::Integer(..)
427 | SpirvType::Float(_)
428 | SpirvType::Pointer { .. } => {
429 let size = ty_def.sizeof(self).unwrap();
430 let primitive = match ty_def {
431 SpirvType::Bool => Primitive::Int(Integer::fit_unsigned(0), false),
432 SpirvType::Integer(int_size, int_signedness) => Primitive::Int(
433 match int_size {
434 8 => Integer::I8,
435 16 => Integer::I16,
436 32 => Integer::I32,
437 64 => Integer::I64,
438 128 => Integer::I128,
439 other => {
440 self.tcx
441 .dcx()
442 .fatal(format!("invalid size for integer: {other}"));
443 }
444 },
445 int_signedness,
446 ),
447 SpirvType::Float(float_size) => Primitive::Float(match float_size {
448 16 => Float::F16,
449 32 => Float::F32,
450 64 => Float::F64,
451 128 => Float::F128,
452 other => {
453 self.tcx
454 .dcx()
455 .fatal(format!("invalid size for float: {other}"));
456 }
457 }),
458 SpirvType::Pointer { .. } => Primitive::Pointer(AddressSpace::ZERO),
459 _ => unreachable!(),
460 };
461
462 let range = alloc_range(offset, size);
463 let read_provenance = matches!(primitive, Primitive::Pointer(_));
464
465 let mut primitive = primitive;
466 let mut read_result = alloc.inner().read_scalar(self, range, read_provenance);
467
468 if read_result.is_err()
472 && !read_provenance
473 && let read_ptr_result @ Ok(Scalar::Ptr(ptr, _)) = alloc
474 .inner()
475 .read_scalar(self, range, true)
476 {
477 let (prov, _offset) = ptr.prov_and_relative_offset();
478 primitive = Primitive::Pointer(
479 self.tcx.global_alloc(prov.alloc_id()).address_space(self),
480 );
481 read_result = read_ptr_result;
482 }
483
484 let scalar_or_zombie = match read_result {
485 Ok(scalar) => {
486 Ok(self.scalar_to_backend(scalar, self.primitive_to_scalar(primitive), ty))
487 }
488
489 Err(err) => match err {
492 AllocError::InvalidUninitBytes(_) => {
496 let uninit_range = alloc
497 .inner()
498 .init_mask()
499 .is_range_initialized(range)
500 .unwrap_err();
501 let uninit_size = {
502 let [start, end] = [uninit_range.start, uninit_range.end()]
503 .map(|x| x.clamp(range.start, range.end()));
504 end - start
505 };
506 if uninit_size == size {
507 Ok(self.undef(ty))
508 } else {
509 Err(format!(
510 "overlaps {} uninitialized bytes",
511 uninit_size.bytes()
512 ))
513 }
514 }
515 AllocError::ReadPointerAsInt(_) => Err("overlaps pointer bytes".into()),
516 AllocError::ReadPartialPointer(_) => {
517 Err("partially overlaps another pointer".into())
518 }
519
520 AllocError::ScalarSizeMismatch(_) => {
523 Err(format!("unrecognized `AllocError::{err:?}`"))
524 }
525 },
526 };
527 let result = scalar_or_zombie.unwrap_or_else(|reason| {
528 let result = self.undef(ty);
529 self.zombie_no_span(
530 result.def_cx(self),
531 &format!("unsupported `{}` constant: {reason}", self.debug_type(ty),),
532 );
533 result
534 });
535 (result, size)
536 }
537 SpirvType::Adt {
538 field_types,
539 field_offsets,
540 ..
541 } => {
542 let mut tail_read_range = ..Size::ZERO;
545 let result = self.constant_composite(
546 ty,
547 field_types
548 .iter()
549 .zip_eq(field_offsets.iter())
550 .map(|(&f_ty, &f_offset)| {
551 let (f, f_size) =
552 self.read_from_const_alloc_at(alloc, f_ty, offset + f_offset);
553 tail_read_range.end =
554 tail_read_range.end.max(offset + f_offset + f_size);
555 f.def_cx(self)
556 }),
557 );
558
559 let ty_size = ty_def.sizeof(self);
560
561 if let Some(ty_size) = ty_size
563 && let Some(tail_gap) = (ty_size.bytes())
564 .checked_sub(tail_read_range.end.align_to(ty_def.alignof(self)).bytes())
565 && tail_gap > 0
566 {
567 self.zombie_no_span(
568 result.def_cx(self),
569 &format!(
570 "undersized `{}` constant (at least {tail_gap} bytes may be missing)",
571 self.debug_type(ty)
572 ),
573 );
574 }
575
576 (result, ty_size.unwrap_or(tail_read_range.end))
577 }
578 SpirvType::Vector { element, .. }
579 | SpirvType::Matrix { element, .. }
580 | SpirvType::Array { element, .. }
581 | SpirvType::RuntimeArray { element } => {
582 let stride = self.lookup_type(element).sizeof(self).unwrap();
583
584 let count = match ty_def {
585 SpirvType::Vector { count, .. } | SpirvType::Matrix { count, .. } => {
586 u64::from(count)
587 }
588 SpirvType::Array { count, .. } => {
589 u64::try_from(self.builder.lookup_const_scalar(count).unwrap()).unwrap()
590 }
591 SpirvType::RuntimeArray { .. } => {
592 (alloc.inner().size() - offset).bytes() / stride.bytes()
593 }
594 _ => unreachable!(),
595 };
596
597 let result = self.constant_composite(
598 ty,
599 (0..count).map(|i| {
600 let (e, e_size) =
601 self.read_from_const_alloc_at(alloc, element, offset + i * stride);
602 assert_eq!(e_size, stride);
603 e.def_cx(self)
604 }),
605 );
606
607 let read_size = (count * stride).align_to(ty_def.alignof(self));
611
612 if let Some(ty_size) = ty_def.sizeof(self) {
613 assert_eq!(read_size, ty_size);
614 }
615
616 if let SpirvType::RuntimeArray { .. } = ty_def {
617 self.zombie_no_span(
622 result.def_cx(self),
623 &format!("unsupported unsized `{}` constant", self.debug_type(ty)),
624 );
625 }
626
627 (result, read_size)
628 }
629
630 SpirvType::Void
631 | SpirvType::Function { .. }
632 | SpirvType::Image { .. }
633 | SpirvType::Sampler
634 | SpirvType::SampledImage { .. }
635 | SpirvType::InterfaceBlock { .. }
636 | SpirvType::AccelerationStructureKhr
637 | SpirvType::RayQueryKhr
638 | SpirvType::CooperativeMatrixKhr { .. } => {
639 let result = self.undef(ty);
640 self.zombie_no_span(
641 result.def_cx(self),
642 &format!(
643 "cannot reinterpret Rust constant data as a `{}` value",
644 self.debug_type(ty)
645 ),
646 );
647 (result, ty_def.sizeof(self).unwrap_or(Size::ZERO))
648 }
649 }
650 }
651}