1use alloc::vec::Vec;
2use core::fmt;
3
4use crate::{
5 BasicBlock, DType, ExtensionSet, Model, Op, Operator, SemanticError, Shape, Target, Tensor,
6 validate_semantics,
7};
8
9macro_rules! index_type {
10 ($name:ident) => {
11 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12 #[repr(transparent)]
13 pub struct $name(u32);
14
15 impl $name {
16 pub const fn get(self) -> u32 {
17 self.0
18 }
19
20 fn from_usize(value: usize) -> Result<Self, AnalysisError> {
21 match u32::try_from(value) {
22 Ok(value) => Ok(Self(value)),
23 Err(_) => Err(AnalysisError::TooManyObjects),
24 }
25 }
26
27 const fn index(self) -> usize {
28 self.0 as usize
29 }
30 }
31 };
32}
33
34index_type!(RegionId);
35index_type!(BlockId);
36index_type!(ValueId);
37index_type!(OperatorId);
38
39#[cfg(test)]
40impl ValueId {
41 pub(crate) const fn from_raw(raw: u32) -> Self {
42 Self(raw)
43 }
44}
45
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub struct AnalysisSpan {
49 start: u32,
50 len: u32,
51}
52
53impl AnalysisSpan {
54 pub const fn start(self) -> u32 {
55 self.start
56 }
57
58 pub const fn len(self) -> usize {
59 self.len as usize
60 }
61
62 pub const fn is_empty(self) -> bool {
63 self.len == 0
64 }
65
66 fn new(start: usize, len: usize) -> Result<Self, AnalysisError> {
67 Ok(Self {
68 start: u32::try_from(start).map_err(|_| AnalysisError::TooManyObjects)?,
69 len: u32::try_from(len).map_err(|_| AnalysisError::TooManyObjects)?,
70 })
71 }
72
73 fn range(self) -> core::ops::Range<usize> {
74 let start = self.start as usize;
75 start..start + self.len as usize
76 }
77}
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub struct AnalysisOptions {
82 pub max_folded_constant_bytes: u64,
84}
85
86impl Default for AnalysisOptions {
87 fn default() -> Self {
88 Self {
89 max_folded_constant_bytes: 1024 * 1024,
90 }
91 }
92}
93
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum AnalysisError {
97 Semantic(SemanticError),
98 AllocationFailed,
99 TooManyObjects,
100}
101
102impl fmt::Display for AnalysisError {
103 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104 write!(formatter, "{self:?}")
105 }
106}
107
108impl From<SemanticError> for AnalysisError {
109 fn from(value: SemanticError) -> Self {
110 Self::Semantic(value)
111 }
112}
113
114#[derive(Clone, Copy, Debug)]
116pub enum AnalyzedValueKind<'a> {
117 Tensor(Tensor<'a>),
118 Shape(Shape<'a>),
119}
120
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub enum ConstantState {
124 NonConstant,
125 Serialized,
127 Foldable,
129}
130
131#[derive(Clone, Copy, Debug)]
133pub struct AnalyzedValue<'a> {
134 id: ValueId,
135 block: BlockId,
136 name: &'a str,
137 kind: AnalyzedValueKind<'a>,
138 producer: Option<OperatorId>,
139 constant: ConstantState,
140 byte_size: Option<u64>,
141 consumers: u32,
142 first_use: Option<u32>,
143 last_use: Option<u32>,
144}
145
146impl<'a> AnalyzedValue<'a> {
147 pub const fn id(&self) -> ValueId {
148 self.id
149 }
150
151 pub const fn block(&self) -> BlockId {
152 self.block
153 }
154
155 pub const fn name(&self) -> &'a str {
156 self.name
157 }
158
159 pub const fn kind(&self) -> AnalyzedValueKind<'a> {
160 self.kind
161 }
162
163 pub const fn producer(&self) -> Option<OperatorId> {
164 self.producer
165 }
166
167 pub const fn constant(&self) -> ConstantState {
168 self.constant
169 }
170
171 pub const fn byte_size(&self) -> Option<u64> {
172 self.byte_size
173 }
174
175 pub const fn consumers(&self) -> u32 {
176 self.consumers
177 }
178
179 pub const fn first_use(&self) -> Option<u32> {
181 self.first_use
182 }
183
184 pub const fn last_use(&self) -> Option<u32> {
187 self.last_use
188 }
189}
190
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub enum RuntimeCondition<'a> {
197 DynamicCompileTimeInput {
198 operator: OperatorId,
199 input_index: u16,
200 value: ValueId,
201 required_error_check: bool,
202 },
203 ShiftInRange {
204 operator: OperatorId,
205 value: ValueId,
206 maximum: u8,
207 },
208 NonZero {
209 operator: OperatorId,
210 value: ValueId,
211 },
212 Int32MultiplyInRange {
213 operator: OperatorId,
214 left: ValueId,
215 right: ValueId,
216 shift: ValueId,
217 },
218 PowDomain {
219 operator: OperatorId,
220 base: ValueId,
221 exponent: ValueId,
222 },
223 IndicesInRange {
224 operator: OperatorId,
225 indices: ValueId,
226 upper_bound: u64,
227 },
228 ScatterIndicesUnique {
229 operator: OperatorId,
230 indices: ValueId,
231 },
232 VariableState {
233 operator: OperatorId,
234 value: ValueId,
235 },
236 Custom {
237 operator: OperatorId,
238 domain: &'a str,
239 name: &'a str,
240 },
241}
242
243impl RuntimeCondition<'_> {
244 pub const fn error_detection_required(self) -> bool {
246 matches!(
247 self,
248 Self::DynamicCompileTimeInput {
249 required_error_check: true,
250 ..
251 }
252 )
253 }
254}
255
256#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
258#[repr(transparent)]
259pub struct OptimizationHints(u16);
260
261impl OptimizationHints {
262 pub const NONE: Self = Self(0);
263 pub const DEAD: Self = Self(1 << 0);
265 pub const ALIAS_INPUT_ZERO: Self = Self(1 << 1);
267 pub const FOLD_CONSTANT: Self = Self(1 << 2);
269 pub const COMPOSE_RESHAPE: Self = Self(1 << 3);
271 pub const COMPOSE_TRANSPOSE: Self = Self(1 << 4);
273 pub const CUSTOM: Self = Self(1 << 5);
275 pub const CONTROL_FLOW: Self = Self(1 << 6);
277
278 pub const fn contains(self, other: Self) -> bool {
279 self.0 & other.0 == other.0
280 }
281
282 const fn with(self, other: Self) -> Self {
283 Self(self.0 | other.0)
284 }
285}
286
287#[derive(Clone, Copy, Debug)]
289pub struct AnalyzedOperator<'a> {
290 id: OperatorId,
291 block: BlockId,
292 source_index: u32,
293 execution_index: u32,
294 op: Op,
295 source: Operator<'a>,
296 inputs: AnalysisSpan,
297 outputs: AnalysisSpan,
298 conditions: AnalysisSpan,
299 hints: OptimizationHints,
300}
301
302impl<'a> AnalyzedOperator<'a> {
303 pub const fn id(&self) -> OperatorId {
304 self.id
305 }
306
307 pub const fn block(&self) -> BlockId {
308 self.block
309 }
310
311 pub const fn source_index(&self) -> u32 {
312 self.source_index
313 }
314
315 pub const fn execution_index(&self) -> u32 {
316 self.execution_index
317 }
318
319 pub const fn op(&self) -> Op {
320 self.op
321 }
322
323 pub const fn source(&self) -> Operator<'a> {
325 self.source
326 }
327
328 pub const fn hints(&self) -> OptimizationHints {
329 self.hints
330 }
331}
332
333#[derive(Clone, Copy, Debug)]
335pub struct AnalyzedBlock<'a> {
336 id: BlockId,
337 region: RegionId,
338 name: &'a str,
339 values: AnalysisSpan,
340 operators: AnalysisSpan,
341 inputs: AnalysisSpan,
342 outputs: AnalysisSpan,
343 execution_order: AnalysisSpan,
344}
345
346impl<'a> AnalyzedBlock<'a> {
347 pub const fn id(&self) -> BlockId {
348 self.id
349 }
350
351 pub const fn region(&self) -> RegionId {
352 self.region
353 }
354
355 pub const fn name(&self) -> &'a str {
356 self.name
357 }
358}
359
360#[derive(Clone, Copy, Debug)]
362pub struct AnalyzedRegion<'a> {
363 id: RegionId,
364 name: &'a str,
365 blocks: AnalysisSpan,
366}
367
368impl<'a> AnalyzedRegion<'a> {
369 pub const fn id(&self) -> RegionId {
370 self.id
371 }
372
373 pub const fn name(&self) -> &'a str {
374 self.name
375 }
376}
377
378#[derive(Debug)]
383pub struct TosaAnalysis<'a> {
384 target: Target,
385 model_bytes: &'a [u8],
386 regions: Vec<AnalyzedRegion<'a>>,
387 blocks: Vec<AnalyzedBlock<'a>>,
388 values: Vec<AnalyzedValue<'a>>,
389 operators: Vec<AnalyzedOperator<'a>>,
390 operands: Vec<ValueId>,
391 block_io: Vec<ValueId>,
392 execution_order: Vec<OperatorId>,
393 conditions: Vec<RuntimeCondition<'a>>,
394}
395
396impl<'a> TosaAnalysis<'a> {
397 pub fn build(model: &Model<'a>, target: Target) -> Result<Self, AnalysisError> {
398 Self::build_with_options(model, target, AnalysisOptions::default())
399 }
400
401 pub fn build_with_options(
402 model: &Model<'a>,
403 target: Target,
404 options: AnalysisOptions,
405 ) -> Result<Self, AnalysisError> {
406 validate_semantics(model, target)?;
407 Builder::new(model, target, options).build()
408 }
409
410 pub const fn target(&self) -> Target {
411 self.target
412 }
413
414 pub fn serialized_constant(&self, id: ValueId) -> Option<&'a [u8]> {
416 let value = self.value(id);
417 if value.constant != ConstantState::Serialized {
418 return None;
419 }
420 match value.kind {
421 AnalyzedValueKind::Tensor(tensor) => {
422 if !tensor.data().is_empty() {
423 return Some(tensor.data());
424 }
425 let (offset, size) = tensor.external_data_range()?;
426 let start = usize::try_from(offset).ok()?;
427 let size = usize::try_from(size).ok()?;
428 self.model_bytes.get(start..start.checked_add(size)?)
429 }
430 AnalyzedValueKind::Shape(shape) => Some(shape.data()),
431 }
432 }
433
434 pub fn regions(&self) -> &[AnalyzedRegion<'a>] {
435 &self.regions
436 }
437
438 pub fn blocks(&self) -> &[AnalyzedBlock<'a>] {
439 &self.blocks
440 }
441
442 pub fn values(&self) -> &[AnalyzedValue<'a>] {
443 &self.values
444 }
445
446 pub fn operators(&self) -> &[AnalyzedOperator<'a>] {
447 &self.operators
448 }
449
450 pub fn conditions(&self) -> &[RuntimeCondition<'a>] {
451 &self.conditions
452 }
453
454 pub fn proves_constant_index_bounds(&self, condition: &RuntimeCondition<'_>) -> bool {
457 let RuntimeCondition::IndicesInRange {
458 indices,
459 upper_bound,
460 ..
461 } = condition
462 else {
463 return false;
464 };
465 let AnalyzedValueKind::Tensor(tensor) = self.value(*indices).kind() else {
466 return false;
467 };
468 if tensor.dtype() != DType::INT32 {
469 return false;
470 }
471 self.serialized_constant(*indices).is_some_and(|bytes| {
472 !bytes.is_empty()
473 && bytes.len() % 4 == 0
474 && bytes.chunks_exact(4).all(|b| {
475 let value = i32::from_le_bytes(b.try_into().unwrap());
476 value >= 0 && (value as u64) < *upper_bound
477 })
478 })
479 }
480
481 pub fn proves_byte_lookup_bounds(&self, condition: &RuntimeCondition<'_>) -> bool {
487 let RuntimeCondition::IndicesInRange {
488 indices,
489 upper_bound,
490 ..
491 } = condition
492 else {
493 return false;
494 };
495 if *upper_bound < 256 {
496 return false;
497 }
498 let Some(add) = self.value(*indices).producer() else {
499 return false;
500 };
501 if self.operator(add).op() != Op::ADD {
502 return false;
503 }
504 let inputs = self.operator_inputs(add);
505 for (cast, offset) in [(inputs[0], inputs[1]), (inputs[1], inputs[0])] {
506 let AnalyzedValueKind::Tensor(offset_tensor) = self.value(offset).kind() else {
507 continue;
508 };
509 if offset_tensor.dtype() != DType::INT32 {
510 continue;
511 }
512 let Some(bytes) = self.serialized_constant(offset) else {
513 continue;
514 };
515 if bytes.is_empty()
516 || bytes.len() % 4 != 0
517 || bytes.chunks_exact(4).any(|b| b != 128i32.to_le_bytes())
518 {
519 continue;
520 }
521 let AnalyzedValueKind::Tensor(cast_tensor) = self.value(cast).kind() else {
522 continue;
523 };
524 if cast_tensor.dtype() != DType::INT32 {
525 continue;
526 }
527 let Some(cast_op) = self.value(cast).producer() else {
528 continue;
529 };
530 if self.operator(cast_op).op() != Op::CAST {
531 continue;
532 }
533 let source = self.operator_inputs(cast_op)[0];
534 if matches!(self.value(source).kind(), AnalyzedValueKind::Tensor(t) if t.dtype() == DType::INT8)
535 {
536 return true;
537 }
538 }
539 false
540 }
541
542 pub fn value(&self, id: ValueId) -> &AnalyzedValue<'a> {
543 &self.values[id.index()]
544 }
545
546 pub fn operator(&self, id: OperatorId) -> &AnalyzedOperator<'a> {
547 &self.operators[id.index()]
548 }
549
550 pub fn operator_inputs(&self, operator: OperatorId) -> &[ValueId] {
551 &self.operands[self.operator(operator).inputs.range()]
552 }
553
554 pub fn operator_outputs(&self, operator: OperatorId) -> &[ValueId] {
555 &self.operands[self.operator(operator).outputs.range()]
556 }
557
558 pub fn operator_conditions(&self, operator: OperatorId) -> &[RuntimeCondition<'a>] {
559 &self.conditions[self.operator(operator).conditions.range()]
560 }
561
562 pub fn block_values(&self, block: BlockId) -> &[AnalyzedValue<'a>] {
563 &self.values[self.blocks[block.index()].values.range()]
564 }
565
566 pub fn block_operators(&self, block: BlockId) -> &[AnalyzedOperator<'a>] {
567 &self.operators[self.blocks[block.index()].operators.range()]
568 }
569
570 pub fn block_inputs(&self, block: BlockId) -> &[ValueId] {
571 &self.block_io[self.blocks[block.index()].inputs.range()]
572 }
573
574 pub fn block_outputs(&self, block: BlockId) -> &[ValueId] {
575 &self.block_io[self.blocks[block.index()].outputs.range()]
576 }
577
578 pub fn execution_order(&self, block: BlockId) -> &[OperatorId] {
579 &self.execution_order[self.blocks[block.index()].execution_order.range()]
580 }
581
582 pub fn region_blocks(&self, region: RegionId) -> &[AnalyzedBlock<'a>] {
583 &self.blocks[self.regions[region.index()].blocks.range()]
584 }
585}
586
587struct Builder<'model, 'a> {
588 model: &'model Model<'a>,
589 target: Target,
590 options: AnalysisOptions,
591 analysis: TosaAnalysis<'a>,
592}
593
594impl<'model, 'a> Builder<'model, 'a> {
595 fn new(model: &'model Model<'a>, target: Target, options: AnalysisOptions) -> Self {
596 Self {
597 model,
598 target,
599 options,
600 analysis: TosaAnalysis {
601 target,
602 model_bytes: model.as_bytes(),
603 regions: Vec::new(),
604 blocks: Vec::new(),
605 values: Vec::new(),
606 operators: Vec::new(),
607 operands: Vec::new(),
608 block_io: Vec::new(),
609 execution_order: Vec::new(),
610 conditions: Vec::new(),
611 },
612 }
613 }
614
615 fn build(mut self) -> Result<TosaAnalysis<'a>, AnalysisError> {
616 reserve(&mut self.analysis.regions, self.model.regions().len())?;
617 reserve(&mut self.analysis.blocks, self.model.stats().blocks)?;
618 reserve(
619 &mut self.analysis.values,
620 self.model.stats().tensors + self.model.stats().shapes,
621 )?;
622 reserve(&mut self.analysis.operators, self.model.stats().operators)?;
623 reserve(&mut self.analysis.operands, self.model.stats().edges)?;
624 reserve(&mut self.analysis.block_io, self.model.stats().edges)?;
625 reserve(
626 &mut self.analysis.execution_order,
627 self.model.stats().operators,
628 )?;
629
630 for region in self.model.regions() {
631 let region_id = RegionId::from_usize(self.analysis.regions.len())?;
632 let block_start = self.analysis.blocks.len();
633 for block in region.blocks() {
634 self.build_block(region_id, block)?;
635 }
636 self.analysis.regions.push(AnalyzedRegion {
637 id: region_id,
638 name: region.name(),
639 blocks: AnalysisSpan::new(block_start, self.analysis.blocks.len() - block_start)?,
640 });
641 }
642 Ok(self.analysis)
643 }
644
645 fn build_block(
646 &mut self,
647 region_id: RegionId,
648 block: BasicBlock<'a>,
649 ) -> Result<(), AnalysisError> {
650 let block_id = BlockId::from_usize(self.analysis.blocks.len())?;
651 let value_start = self.analysis.values.len();
652 let operator_start = self.analysis.operators.len();
653 let mut symbols = Vec::new();
654 reserve(&mut symbols, block.tensors().len() + block.shapes().len())?;
655
656 for tensor in block.tensors() {
657 let id = ValueId::from_usize(self.analysis.values.len())?;
658 let byte_size = tensor_byte_size(tensor);
659 self.analysis.values.push(AnalyzedValue {
660 id,
661 block: block_id,
662 name: tensor.name(),
663 kind: AnalyzedValueKind::Tensor(tensor),
664 producer: None,
665 constant: ConstantState::NonConstant,
666 byte_size,
667 consumers: 0,
668 first_use: None,
669 last_use: None,
670 });
671 symbols.push((tensor.name(), id));
672 }
673 for shape in block.shapes() {
674 let id = ValueId::from_usize(self.analysis.values.len())?;
675 self.analysis.values.push(AnalyzedValue {
676 id,
677 block: block_id,
678 name: shape.name(),
679 kind: AnalyzedValueKind::Shape(shape),
680 producer: None,
681 constant: ConstantState::NonConstant,
682 byte_size: Some(u64::from(shape.rank()) * 8),
683 consumers: 0,
684 first_use: None,
685 last_use: None,
686 });
687 symbols.push((shape.name(), id));
688 }
689 symbols.sort_unstable_by_key(|(name, _)| *name);
690
691 let input_start = self.analysis.block_io.len();
692 for name in block.inputs() {
693 self.analysis.block_io.push(resolve(&symbols, name));
694 }
695 let input_span =
696 AnalysisSpan::new(input_start, self.analysis.block_io.len() - input_start)?;
697 let output_start = self.analysis.block_io.len();
698 for name in block.outputs() {
699 self.analysis.block_io.push(resolve(&symbols, name));
700 }
701 let output_span =
702 AnalysisSpan::new(output_start, self.analysis.block_io.len() - output_start)?;
703
704 let local_operator_count = block.operators().len();
705 let mut local_inputs = Vec::new();
706 let mut local_outputs = Vec::new();
707 reserve(&mut local_inputs, local_operator_count)?;
708 reserve(&mut local_outputs, local_operator_count)?;
709 for (source_index, operator) in block.operators().enumerate() {
710 let id = OperatorId::from_usize(self.analysis.operators.len())?;
711 let inputs_start = self.analysis.operands.len();
712 for name in operator.inputs() {
713 self.analysis.operands.push(resolve(&symbols, name));
714 }
715 let inputs =
716 AnalysisSpan::new(inputs_start, self.analysis.operands.len() - inputs_start)?;
717 let outputs_start = self.analysis.operands.len();
718 for name in operator.outputs() {
719 let value = resolve(&symbols, name);
720 self.analysis.operands.push(value);
721 if !matches!(self.analysis.values[value.index()].kind, AnalyzedValueKind::Tensor(tensor) if tensor.is_variable())
722 {
723 self.analysis.values[value.index()].producer = Some(id);
724 }
725 }
726 let outputs =
727 AnalysisSpan::new(outputs_start, self.analysis.operands.len() - outputs_start)?;
728 if matches!(operator.op(), Op::CONST | Op::CONST_SHAPE) {
729 for value in &self.analysis.operands[outputs.range()] {
730 self.analysis.values[value.index()].constant = ConstantState::Serialized;
731 }
732 }
733 self.analysis.operators.push(AnalyzedOperator {
734 id,
735 block: block_id,
736 source_index: u32::try_from(source_index)
737 .map_err(|_| AnalysisError::TooManyObjects)?,
738 execution_index: 0,
739 op: operator.op(),
740 source: operator,
741 inputs,
742 outputs,
743 conditions: AnalysisSpan::default(),
744 hints: OptimizationHints::NONE,
745 });
746 local_inputs.push(inputs);
747 local_outputs.push(outputs);
748 }
749
750 for (local_index, operator) in block.operators().enumerate() {
751 let operator_index = operator_start + local_index;
752 let analyzed = self.analysis.operators[operator_index];
753 let condition_start = self.analysis.conditions.len();
754 add_conditions(
755 ConditionContext {
756 target: self.target,
757 operator: analyzed.id,
758 op: analyzed.op,
759 attributes: operator.attributes(),
760 inputs: &self.analysis.operands[analyzed.inputs.range()],
761 outputs: &self.analysis.operands[analyzed.outputs.range()],
762 values: &self.analysis.values,
763 },
764 &mut self.analysis.conditions,
765 )?;
766 self.analysis.operators[operator_index].conditions = AnalysisSpan::new(
767 condition_start,
768 self.analysis.conditions.len() - condition_start,
769 )?;
770 }
771
772 let order = topological_order(
773 operator_start,
774 &local_inputs,
775 &self.analysis.values,
776 &self.analysis.operands,
777 local_operator_count,
778 )?;
779 let execution_start = self.analysis.execution_order.len();
780 for (position, local_index) in order.iter().copied().enumerate() {
781 let operator_index = operator_start + local_index;
782 let operator_id = self.analysis.operators[operator_index].id;
783 self.analysis.operators[operator_index].execution_index =
784 u32::try_from(position).map_err(|_| AnalysisError::TooManyObjects)?;
785 self.analysis.execution_order.push(operator_id);
786 let input_span = self.analysis.operators[operator_index].inputs;
787 for value in &self.analysis.operands[input_span.range()] {
788 let value = &mut self.analysis.values[value.index()];
789 value.consumers = value
790 .consumers
791 .checked_add(1)
792 .ok_or(AnalysisError::TooManyObjects)?;
793 let position =
794 u32::try_from(position).map_err(|_| AnalysisError::TooManyObjects)?;
795 value.first_use.get_or_insert(position);
796 value.last_use = Some(position);
797 }
798 self.propagate_constants(operator_index)?;
799 }
800 let block_end =
801 u32::try_from(local_operator_count).map_err(|_| AnalysisError::TooManyObjects)?;
802 for value in &self.analysis.block_io[output_span.range()] {
803 self.analysis.values[value.index()].last_use = Some(block_end);
804 }
805 let mut output_values = Vec::new();
806 reserve(&mut output_values, output_span.len())?;
807 output_values.extend_from_slice(&self.analysis.block_io[output_span.range()]);
808 self.mark_live_and_hints(operator_start, &order, &output_values)?;
809
810 self.analysis.blocks.push(AnalyzedBlock {
811 id: block_id,
812 region: region_id,
813 name: block.name(),
814 values: AnalysisSpan::new(value_start, self.analysis.values.len() - value_start)?,
815 operators: AnalysisSpan::new(
816 operator_start,
817 self.analysis.operators.len() - operator_start,
818 )?,
819 inputs: input_span,
820 outputs: output_span,
821 execution_order: AnalysisSpan::new(
822 execution_start,
823 self.analysis.execution_order.len() - execution_start,
824 )?,
825 });
826 Ok(())
827 }
828
829 fn propagate_constants(&mut self, operator_index: usize) -> Result<(), AnalysisError> {
830 let operator = self.analysis.operators[operator_index];
831 if !foldable_operator(operator.op)
832 || !self.analysis.operands[operator.inputs.range()]
833 .iter()
834 .all(|value| {
835 self.analysis.values[value.index()].constant != ConstantState::NonConstant
836 })
837 {
838 return Ok(());
839 }
840 let total_bytes = self.analysis.operands[operator.outputs.range()]
841 .iter()
842 .try_fold(0_u64, |total, value| {
843 total.checked_add(self.analysis.values[value.index()].byte_size?)
844 });
845 if total_bytes.is_some_and(|bytes| bytes <= self.options.max_folded_constant_bytes) {
846 self.analysis.operators[operator_index].hints = self.analysis.operators[operator_index]
847 .hints
848 .with(OptimizationHints::FOLD_CONSTANT);
849 for value in &self.analysis.operands[operator.outputs.range()] {
850 self.analysis.values[value.index()].constant = ConstantState::Foldable;
851 }
852 }
853 Ok(())
854 }
855
856 fn mark_live_and_hints(
857 &mut self,
858 operator_start: usize,
859 order: &[usize],
860 block_outputs: &[ValueId],
861 ) -> Result<(), AnalysisError> {
862 let mut live = Vec::new();
863 reserve(&mut live, order.len())?;
864 live.resize(order.len(), false);
865 for value in block_outputs {
866 if let Some(producer) = self.analysis.values[value.index()].producer {
867 live[producer.index() - operator_start] = true;
868 }
869 }
870 for &local_index in order {
871 let op = self.analysis.operators[operator_start + local_index].op;
872 if has_side_effects(op) {
873 live[local_index] = true;
874 }
875 }
876 for &local_index in order.iter().rev() {
877 let operator_index = operator_start + local_index;
878 if live[local_index] {
879 let inputs = self.analysis.operators[operator_index].inputs;
880 for value in &self.analysis.operands[inputs.range()] {
881 if let Some(producer) = self.analysis.values[value.index()].producer {
882 live[producer.index() - operator_start] = true;
883 }
884 }
885 } else {
886 self.analysis.operators[operator_index].hints = self.analysis.operators
887 [operator_index]
888 .hints
889 .with(OptimizationHints::DEAD);
890 }
891 }
892
893 for &local_index in order {
894 let operator_index = operator_start + local_index;
895 let operator = self.analysis.operators[operator_index];
896 let mut hints = operator.hints;
897 if matches!(operator.op, Op::IDENTITY | Op::RESHAPE) {
898 hints = hints.with(OptimizationHints::ALIAS_INPUT_ZERO);
899 }
900 if operator.op == Op::CUSTOM {
901 hints = hints.with(OptimizationHints::CUSTOM);
902 }
903 if matches!(operator.op, Op::COND_IF | Op::WHILE_LOOP) {
904 hints = hints.with(OptimizationHints::CONTROL_FLOW);
905 }
906 let inputs = &self.analysis.operands[operator.inputs.range()];
907 if let Some(input) = inputs.first() {
908 if self.analysis.values[input.index()].consumers == 1 {
909 if let Some(producer) = self.analysis.values[input.index()].producer {
910 let producer_op = self.analysis.operators[producer.index()].op;
911 if operator.op == Op::RESHAPE && producer_op == Op::RESHAPE {
912 hints = hints.with(OptimizationHints::COMPOSE_RESHAPE);
913 }
914 if operator.op == Op::TRANSPOSE && producer_op == Op::TRANSPOSE {
915 hints = hints.with(OptimizationHints::COMPOSE_TRANSPOSE);
916 }
917 }
918 }
919 }
920 self.analysis.operators[operator_index].hints = hints;
921 }
922 Ok(())
923 }
924}
925
926fn reserve<T>(values: &mut Vec<T>, additional: usize) -> Result<(), AnalysisError> {
927 values
928 .try_reserve_exact(additional)
929 .map_err(|_| AnalysisError::AllocationFailed)
930}
931
932fn resolve(symbols: &[(&str, ValueId)], name: &str) -> ValueId {
933 symbols[symbols
934 .binary_search_by_key(&name, |(candidate, _)| *candidate)
935 .expect("semantically validated symbol")]
936 .1
937}
938
939fn topological_order(
940 operator_start: usize,
941 inputs: &[AnalysisSpan],
942 values: &[AnalyzedValue<'_>],
943 operands: &[ValueId],
944 operator_count: usize,
945) -> Result<Vec<usize>, AnalysisError> {
946 let mut indegrees = Vec::new();
947 reserve(&mut indegrees, operator_count)?;
948 indegrees.resize(operator_count, 0_usize);
949 let mut edges = Vec::new();
950 let edge_count = inputs
951 .iter()
952 .try_fold(0_usize, |count, span| count.checked_add(span.len()))
953 .ok_or(AnalysisError::TooManyObjects)?;
954 reserve(&mut edges, edge_count)?;
955 for (consumer, span) in inputs.iter().copied().enumerate() {
956 for value in &operands[span.range()] {
957 if let Some(producer) = values[value.index()].producer {
958 let producer = producer
959 .index()
960 .checked_sub(operator_start)
961 .ok_or(AnalysisError::TooManyObjects)?;
962 edges.push((producer, consumer));
963 indegrees[consumer] = indegrees[consumer]
964 .checked_add(1)
965 .ok_or(AnalysisError::TooManyObjects)?;
966 }
967 }
968 }
969 edges.sort_unstable();
970 let mut order = Vec::new();
971 reserve(&mut order, operator_count)?;
972 order.extend(
973 indegrees
974 .iter()
975 .enumerate()
976 .filter_map(|(index, indegree)| (*indegree == 0).then_some(index)),
977 );
978 let mut cursor = 0;
979 while cursor < order.len() {
980 let producer = order[cursor];
981 cursor += 1;
982 let start = edges.partition_point(|(candidate, _)| *candidate < producer);
983 let end = edges.partition_point(|(candidate, _)| *candidate <= producer);
984 for &(_, consumer) in &edges[start..end] {
985 indegrees[consumer] -= 1;
986 if indegrees[consumer] == 0 {
987 order.push(consumer);
988 }
989 }
990 }
991 if order.len() == operator_count {
992 Ok(order)
993 } else {
994 Err(AnalysisError::TooManyObjects)
996 }
997}
998
999fn tensor_byte_size(tensor: Tensor<'_>) -> Option<u64> {
1000 let _ = tensor.rank()?;
1001 let elements = tensor.dimensions().try_fold(1_u64, |count, dimension| {
1002 count.checked_mul(u64::try_from(dimension).ok()?)
1003 })?;
1004 let bytes = match tensor.dtype() {
1005 DType::INT4 => return elements.checked_add(1).map(|value| value / 2),
1006 DType::BOOL | DType::INT8 | DType::FP8E4M3 | DType::FP8E5M2 => 1,
1007 DType::INT16 | DType::FP16 | DType::BF16 => 2,
1008 DType::INT32 | DType::FP32 => 4,
1009 DType::INT48 => 6,
1010 _ => return None,
1011 };
1012 elements.checked_mul(bytes)
1013}
1014
1015fn foldable_operator(op: Op) -> bool {
1016 matches!(
1017 op,
1018 Op::IDENTITY
1019 | Op::RESHAPE
1020 | Op::TRANSPOSE
1021 | Op::REVERSE
1022 | Op::SLICE
1023 | Op::TILE
1024 | Op::CONCAT
1025 )
1026}
1027
1028fn has_side_effects(op: Op) -> bool {
1029 matches!(
1030 op,
1031 Op::CUSTOM
1032 | Op::COND_IF
1033 | Op::WHILE_LOOP
1034 | Op::VARIABLE
1035 | Op::VARIABLE_READ
1036 | Op::VARIABLE_WRITE
1037 )
1038}
1039
1040struct ConditionContext<'a, 'plan> {
1041 target: Target,
1042 operator: OperatorId,
1043 op: Op,
1044 attributes: crate::OpAttributes<'a>,
1045 inputs: &'plan [ValueId],
1046 outputs: &'plan [ValueId],
1047 values: &'plan [AnalyzedValue<'a>],
1048}
1049
1050fn add_conditions<'a>(
1051 context: ConditionContext<'a, '_>,
1052 conditions: &mut Vec<RuntimeCondition<'a>>,
1053) -> Result<(), AnalysisError> {
1054 let ConditionContext {
1055 target,
1056 operator,
1057 op,
1058 attributes,
1059 inputs,
1060 outputs,
1061 values,
1062 } = context;
1063 let dynamic = target.extensions.contains(ExtensionSet::DYNAMIC);
1064 if dynamic {
1065 for &input_index in ctc_inputs(op) {
1066 let value = inputs[input_index];
1067 if values[value.index()].constant != ConstantState::Serialized {
1068 conditions
1069 .try_reserve(1)
1070 .map_err(|_| AnalysisError::AllocationFailed)?;
1071 conditions.push(RuntimeCondition::DynamicCompileTimeInput {
1072 operator,
1073 input_index: u16::try_from(input_index)
1074 .map_err(|_| AnalysisError::TooManyObjects)?,
1075 value,
1076 required_error_check: dynamic_ctc_requires_error(op, input_index),
1077 });
1078 }
1079 }
1080 }
1081 let mut push = |condition| -> Result<(), AnalysisError> {
1082 conditions
1083 .try_reserve(1)
1084 .map_err(|_| AnalysisError::AllocationFailed)?;
1085 conditions.push(condition);
1086 Ok(())
1087 };
1088 match op {
1089 Op::ARITHMETIC_RIGHT_SHIFT | Op::LOGICAL_LEFT_SHIFT | Op::LOGICAL_RIGHT_SHIFT => {
1090 let maximum = match values[inputs[0].index()].kind {
1091 AnalyzedValueKind::Tensor(tensor) if tensor.dtype() == DType::INT32 => 31,
1092 AnalyzedValueKind::Tensor(tensor) if tensor.dtype() == DType::INT16 => 15,
1093 _ => 7,
1094 };
1095 push(RuntimeCondition::ShiftInRange {
1096 operator,
1097 value: inputs[1],
1098 maximum,
1099 })?;
1100 }
1101 Op::INTDIV => push(RuntimeCondition::NonZero {
1102 operator,
1103 value: inputs[1],
1104 })?,
1105 Op::MUL
1106 if matches!(
1107 values[inputs[0].index()].kind,
1108 AnalyzedValueKind::Tensor(tensor) if tensor.dtype() == DType::INT32
1109 ) =>
1110 {
1111 push(RuntimeCondition::Int32MultiplyInRange {
1112 operator,
1113 left: inputs[0],
1114 right: inputs[1],
1115 shift: inputs[2],
1116 })?;
1117 }
1118 Op::POW => push(RuntimeCondition::PowDomain {
1119 operator,
1120 base: inputs[0],
1121 exponent: inputs[1],
1122 })?,
1123 Op::GATHER | Op::SCATTER => {
1124 let data = match values[inputs[0].index()].kind {
1125 AnalyzedValueKind::Tensor(tensor) => tensor,
1126 AnalyzedValueKind::Shape(_) => unreachable!(),
1127 };
1128 let upper_bound = data.dimensions().nth(1).unwrap_or(0) as u64;
1129 push(RuntimeCondition::IndicesInRange {
1130 operator,
1131 indices: inputs[1],
1132 upper_bound,
1133 })?;
1134 if op == Op::SCATTER {
1135 push(RuntimeCondition::ScatterIndicesUnique {
1136 operator,
1137 indices: inputs[1],
1138 })?;
1139 }
1140 }
1141 Op::VARIABLE_WRITE => push(RuntimeCondition::VariableState {
1142 operator,
1143 value: inputs[0],
1144 })?,
1145 Op::VARIABLE_READ => {
1146 if let Some(value) = outputs.first() {
1147 push(RuntimeCondition::VariableState {
1148 operator,
1149 value: *value,
1150 })?;
1151 }
1152 }
1153 Op::CUSTOM => {
1154 let crate::OpAttributes::Custom {
1155 operator_name,
1156 domain_name,
1157 ..
1158 } = attributes
1159 else {
1160 unreachable!()
1161 };
1162 push(RuntimeCondition::Custom {
1163 operator,
1164 domain: domain_name.unwrap_or(""),
1165 name: operator_name.unwrap_or(""),
1166 })?;
1167 }
1168 _ => {}
1169 }
1170 Ok(())
1171}
1172
1173fn ctc_inputs(op: Op) -> &'static [usize] {
1174 match op.get() {
1175 2 => &[1, 2],
1176 3..=5 | 10 => &[3, 4],
1177 7 => &[2, 3],
1178 28 => &[2],
1179 31 => &[1],
1180 41 => &[1, 2],
1181 56 => &[1, 2],
1182 57 => &[1],
1183 59 => &[1, 2],
1184 60 => &[1],
1185 64 => &[1, 2, 3],
1186 66 => &[1, 2, 3, 4],
1187 _ => &[],
1188 }
1189}
1190
1191const fn dynamic_ctc_requires_error(op: Op, input_index: usize) -> bool {
1192 match op.get() {
1193 2..=5 | 7 | 10 | 41 | 56..=57 | 59..=60 | 64 => true,
1194 66 => input_index >= 3,
1195 28 | 31 => false,
1196 _ => false,
1197 }
1198}