Skip to main content

pliron_spirv/
lib.rs

1#![no_std]
2
3extern crate alloc;
4extern crate std;
5
6use core::{
7    cell::Ref,
8    ops::{Deref, DerefMut},
9};
10
11use alloc::{
12    boxed::Box,
13    string::{String, ToString},
14    vec::Vec,
15};
16use pliron::{
17    attribute::{AttrObj, Attribute},
18    basic_block::BasicBlock,
19    builtin::attributes::VecAttr,
20    context::{Context, Ptr},
21    derive::{attr_interface, op_interface, type_interface},
22    identifier::Identifier,
23    input_err_noloc,
24    op::{Op, op_cast},
25    operation::Operation,
26    printable::Printable,
27    result::Result,
28    r#type::{Type, TypeHandle, type_cast},
29    utils::table::{HMap, IMap},
30    value::Value,
31    verify_err,
32    verify_error_noloc,
33};
34use thiserror::Error;
35use tracel_rspirv::{
36    dr::{Builder, Module},
37    spirv::{MemoryAccess, Word},
38};
39
40pub use tracel_rspirv::spirv;
41
42use crate::types::normalize_int_type;
43
44mod autogen_attrs;
45mod autogen_decorations;
46mod autogen_ops;
47
48pub mod attrs;
49pub mod debug_info;
50pub mod decorations;
51pub mod ext;
52mod format;
53pub mod interfaces;
54pub mod ops;
55pub mod tensor_addressing_nv;
56pub mod types;
57pub mod util;
58
59#[derive(Error, Debug)]
60pub enum PlironSpirvError {
61    #[error("Unresolved symbol reference @{_0}")]
62    UnresolvedSymbol(Identifier),
63    #[error("Global symbol @{_0} failed to be registered")]
64    SymbolNotRegistered(Identifier),
65}
66
67#[derive(Default)]
68pub struct PlironBuilder {
69    builder: Builder,
70    types: IMap<TypeHandle, Word>,
71    constants: HMap<(TypeHandle, u64), Word>,
72    values: HMap<Value, Word>,
73    symbols: HMap<Identifier, Word>,
74    blocks: HMap<(Ptr<BasicBlock>, BlockPos), Word>,
75    strings: HMap<String, Word>,
76    debug: Option<Box<debug_info::DebugInfo>>,
77}
78
79impl Deref for PlironBuilder {
80    type Target = Builder;
81
82    fn deref(&self) -> &Self::Target {
83        &self.builder
84    }
85}
86
87impl DerefMut for PlironBuilder {
88    fn deref_mut(&mut self) -> &mut Self::Target {
89        &mut self.builder
90    }
91}
92
93#[derive(Clone, Copy, PartialEq, Eq, Hash)]
94pub(crate) enum BlockPos {
95    Start,
96    End,
97    /// The block that a loop header's ops start in, after the header's phis and merge
98    /// instruction.
99    Body,
100}
101
102impl PlironBuilder {
103    pub fn new() -> Self {
104        Default::default()
105    }
106
107    /// Creates a builder that converts the location of each op to debug data. `options` selects
108    /// the format and the contents. See [`debug_info`] for the rules.
109    #[must_use]
110    pub fn with_debug_info(options: debug_info::DebugInfoOptions) -> Self {
111        Self {
112            debug: Some(Box::new(debug_info::DebugInfo::new(options))),
113            ..Default::default()
114        }
115    }
116
117    pub(crate) fn value_id(&mut self, value: Value) -> Word {
118        if let Some(existing) = self.values.get(&value) {
119            *existing
120        } else {
121            let id = self.id();
122            self.values.insert(value, id);
123            id
124        }
125    }
126
127    pub(crate) fn merge_values(&mut self, value_1: Value, value_2: Value) {
128        match (self.values.get(&value_1), self.values.get(&value_2)) {
129            (Some(_), Some(_)) => panic!("Both values already have IDs"),
130            (Some(id), None) => self.values.insert(value_2, *id),
131            (None, Some(id)) => self.values.insert(value_1, *id),
132            (None, None) => {
133                let id = self.value_id(value_1);
134                self.values.insert(value_2, id)
135            }
136        };
137    }
138
139    pub(crate) fn symbol_id(&mut self, symbol: impl Into<Identifier>) -> Word {
140        let sym = symbol.into();
141        if let Some(existing) = self.symbols.get(&sym) {
142            *existing
143        } else {
144            let id = self.id();
145            self.symbols.insert(sym, id);
146            id
147        }
148    }
149
150    pub(crate) fn label_id(&mut self, block: Ptr<BasicBlock>, pos: BlockPos) -> Word {
151        if let Some(existing) = self.blocks.get(&(block, pos)) {
152            *existing
153        } else {
154            let id = self.id();
155            self.blocks.insert((block, pos), id);
156            id
157        }
158    }
159
160    pub(crate) fn string_ref(&mut self, string: impl Into<String>) -> Word {
161        let string = string.into();
162        if let Some(existing) = self.strings.get(&string) {
163            *existing
164        } else {
165            let id = self.string(string.clone());
166            self.strings.insert(string, id);
167            id
168        }
169    }
170
171    /// Appends an OpConstant instruction with the given 32-bit bit pattern `value`.
172    pub fn constant_bit32(&mut self, ctx: &Context, result_type: TypeHandle, value: u32) -> Result<Word> {
173        let result_type = normalize_int_type(ctx, result_type);
174        if let Some(existing) = self.constants.get(&(result_type, value as u64)) {
175            Ok(*existing)
176        } else {
177            let ty = spirv_type_id(ctx, self, result_type)?;
178            let id = self.builder.constant_bit32(ty, value);
179            self.constants.insert((result_type, value as u64), id);
180            Ok(id)
181        }
182    }
183
184    /// Appends an OpConstant instruction with the given 64-bit bit pattern `value`.
185    pub fn constant_bit64(&mut self, ctx: &Context, result_type: TypeHandle, value: u64) -> Result<Word> {
186        let result_type = normalize_int_type(ctx, result_type);
187        if let Some(existing) = self.constants.get(&(result_type, value)) {
188            Ok(*existing)
189        } else {
190            let ty = spirv_type_id(ctx, self, result_type)?;
191            let id = self.builder.constant_bit64(ty, value);
192            self.constants.insert((result_type, value), id);
193            Ok(id)
194        }
195    }
196
197    pub fn module(mut self) -> Module {
198        debug_info::finish(&mut self);
199        self.builder.module()
200    }
201}
202
203pub trait IntoPlironResult<T> {
204    fn into_pliron_result(self) -> Result<T>;
205}
206
207impl<T> IntoPlironResult<T> for core::result::Result<T, tracel_rspirv::dr::Error> {
208    fn into_pliron_result(self) -> Result<T> {
209        self.map_err(|err| verify_error_noloc!(err))
210    }
211}
212
213impl IntoPlironResult<()> for () {
214    fn into_pliron_result(self) -> Result<()> {
215        Ok(())
216    }
217}
218
219impl IntoPlironResult<u32> for u32 {
220    fn into_pliron_result(self) -> Result<u32> {
221        Ok(self)
222    }
223}
224
225#[derive(Error, Debug)]
226pub enum ToSpirvError {
227    #[error("{_0} doesn't support conversion to SPIR-V")]
228    UnsupportedOp(String),
229    #[error("Found unsupported op {_0} after resolving symbol")]
230    UnsupportedSymbolOp(String),
231    #[error("{_0} doesn't support conversion to SPIR-V")]
232    UnsupportedType(String),
233}
234
235#[op_interface]
236pub trait ToSpirvOp {
237    fn to_spirv(&self, ctx: &Context, builder: &mut PlironBuilder) -> Result<()>;
238
239    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
240    where
241        Self: Sized,
242    {
243        Ok(())
244    }
245}
246
247#[type_interface]
248pub trait ToSpirvType {
249    fn to_spirv(&self, ctx: &Context, builder: &mut PlironBuilder) -> Result<Word>;
250
251    fn verify(_ty: &dyn Type, _ctx: &Context) -> Result<()>
252    where
253        Self: Sized,
254    {
255        Ok(())
256    }
257}
258
259#[attr_interface]
260pub trait ToSpirvAttr {
261    fn to_spirv(&self, ctx: &Context, builder: &mut PlironBuilder) -> Result<Word>;
262
263    fn verify(_attr: &dyn Attribute, _ctx: &Context) -> Result<()>
264    where
265        Self: Sized,
266    {
267        Ok(())
268    }
269}
270
271pub(crate) fn spirv_type_id(ctx: &Context, builder: &mut PlironBuilder, handle: TypeHandle) -> Result<Word> {
272    let handle = normalize_int_type(ctx, handle);
273    if let Some(existing) = builder.types.get(&handle) {
274        Ok(*existing)
275    } else {
276        let ty = handle.deref(ctx);
277        let Some(ty) = type_cast::<dyn ToSpirvType>(&*ty) else {
278            let err = ToSpirvError::UnsupportedType(handle.disp(ctx).to_string());
279            return input_err_noloc!(err);
280        };
281        let id = ty.to_spirv(ctx, builder)?;
282        builder.types.insert(handle, id);
283        Ok(id)
284    }
285}
286
287pub(crate) fn op_to_spirv(ctx: &Context, builder: &mut PlironBuilder, op: Ptr<Operation>) -> Result<()> {
288    let dyn_op = Operation::get_op_dyn(op, ctx);
289    let Some(to_spirv) = op_cast::<dyn ToSpirvOp>(&*dyn_op) else {
290        let error = ToSpirvError::UnsupportedOp(op.disp(ctx).to_string());
291        return verify_err!(dyn_op.loc(ctx), error);
292    };
293    if builder.debug.is_some() {
294        return debug_info::convert_op(ctx, builder, op, |builder| to_spirv.to_spirv(ctx, builder));
295    }
296    to_spirv.to_spirv(ctx, builder)
297}
298
299pub(crate) fn opt_memory_access(mem_access: MemoryAccess) -> Option<MemoryAccess> {
300    if mem_access == MemoryAccess::NONE {
301        None
302    } else {
303        Some(mem_access)
304    }
305}
306
307pub(crate) fn as_vec_attr<T: Attribute>(values: impl IntoIterator<Item = T>) -> VecAttr {
308    VecAttr(values.into_iter().map(|it| -> AttrObj { Box::new(it) }).collect())
309}
310
311pub(crate) fn from_vec_attr<T: Attribute>(attr: Ref<'_, VecAttr>) -> Vec<T> {
312    attr.0
313        .clone()
314        .into_iter()
315        .map(|it| *it.downcast::<T>().unwrap())
316        .collect()
317}
318
319pub(crate) mod prelude {
320    pub(crate) use crate::{
321        IntoPlironResult,
322        PlironBuilder,
323        ToSpirvOp,
324        as_vec_attr,
325        attrs::*,
326        decorations::DecoratableOp,
327        from_vec_attr,
328        interfaces::VerCapExtOpInterface,
329        opt_memory_access,
330        spirv_type_id,
331        util::flat_vec,
332    };
333    pub(crate) use alloc::{
334        string::{String, ToString},
335        vec,
336        vec::Vec,
337    };
338    pub(crate) use pliron::{
339        builtin::{
340            attributes::{IdentifierAttr, StringAttr, UnitAttr, VecAttr},
341            op_interfaces::*,
342        },
343        context::Context,
344        derive::*,
345        identifier::Identifier,
346        op::Op,
347        operation::Operation,
348        result::Result,
349        r#type::{TypeHandle, Typed},
350        value::Value,
351    };
352    pub(crate) use tracel_rspirv::{
353        dr::Operand,
354        spirv::{Capability, Decoration},
355    };
356}