1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
use crate::output_stream::OutputStream;
use arrayvec::ArrayVec;
use rustpython_bytecode::bytecode::{CodeObject, Instruction, Label, Location};

pub mod optimizations;

const PEEPHOLE_BUFFER_SIZE: usize = 20;

pub struct InstructionMetadata {
    loc: Location,
    labels: Vec<Label>,
}

impl From<Vec<InstructionMetadata>> for InstructionMetadata {
    fn from(metas: Vec<Self>) -> Self {
        debug_assert!(!metas.is_empty(), "`metas` must not be empty");
        InstructionMetadata {
            loc: metas[0].loc.clone(),
            labels: metas
                .into_iter()
                .flat_map(|meta| meta.labels.into_iter())
                .collect(),
        }
    }
}
impl From<Location> for InstructionMetadata {
    fn from(loc: Location) -> Self {
        InstructionMetadata {
            loc,
            labels: Vec::new(),
        }
    }
}

pub(crate) struct PeepholeOptimizer<O: OutputStream> {
    inner: O,
    buffer: ArrayVec<[(Instruction, InstructionMetadata); PEEPHOLE_BUFFER_SIZE]>,
}

impl<O: OutputStream> From<CodeObject> for PeepholeOptimizer<O> {
    fn from(code: CodeObject) -> Self {
        Self::new(code.into())
    }
}
impl<O: OutputStream> From<PeepholeOptimizer<O>> for CodeObject {
    fn from(mut peep: PeepholeOptimizer<O>) -> Self {
        peep.flush();
        peep.inner.into()
    }
}

#[macro_export]
macro_rules! apply_optimizations {
    ($buf:expr, $($opt:ident),*$(,)?) => {{
        $($crate::peephole::optimizations::$opt($buf);)*
    }};
}

impl<O: OutputStream> PeepholeOptimizer<O> {
    pub fn new(inner: O) -> Self {
        PeepholeOptimizer {
            inner,
            buffer: ArrayVec::default(),
        }
    }

    fn inner_emit(inner: &mut O, instruction: Instruction, meta: InstructionMetadata) {
        inner.emit(instruction, meta.loc);
        for label in meta.labels {
            inner.set_label(label);
        }
    }

    fn push(&mut self, instruction: Instruction, meta: InstructionMetadata) {
        if self.buffer.is_full() {
            let (instr, meta) = self.buffer.remove(0);
            Self::inner_emit(&mut self.inner, instr, meta);
        }
        self.buffer.push((instruction, meta));
    }

    fn pop(&mut self) -> (Instruction, InstructionMetadata) {
        self.buffer
            .pop()
            .expect("Failed to pop instruction from PeepholeOptimizer buffer")
    }

    fn flush(&mut self) {
        for (instruction, meta) in self.buffer.drain(..) {
            Self::inner_emit(&mut self.inner, instruction, meta);
        }
    }

    fn optimize(&mut self) {
        apply_optimizations!(self, operator, unpack);
    }
}

impl<O> OutputStream for PeepholeOptimizer<O>
where
    O: OutputStream,
{
    fn emit(&mut self, instruction: Instruction, loc: Location) {
        self.push(instruction, loc.into());
        self.optimize();
    }
    fn set_label(&mut self, label: Label) {
        if let Some(instr) = self.buffer.last_mut() {
            instr.1.labels.push(label)
        }
    }
    fn mark_generator(&mut self) {
        self.inner.mark_generator()
    }
}

impl<O: OutputStream> OptimizationBuffer for PeepholeOptimizer<O> {
    fn emit(&mut self, instruction: Instruction, meta: InstructionMetadata) {
        self.push(instruction, meta);
    }
    fn pop(&mut self) -> (Instruction, InstructionMetadata) {
        self.pop()
    }
}

pub trait OptimizationBuffer {
    fn emit(&mut self, instruction: Instruction, meta: InstructionMetadata);
    fn pop(&mut self) -> (Instruction, InstructionMetadata);
}