neo-decompiler 0.6.2

Minimal tooling for inspecting Neo N3 NEF bytecode
Documentation
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! SSA construction from a CFG and instruction stream.
//!
//! Implements the two-phase SSA construction algorithm:
//! 1. φ node insertion using dominance frontiers
//! 2. Variable renaming via dominator tree traversal
//!
//! # Current limitations
//!
//! The builder currently produces a **skeleton** SSA form: only `Push0`–`Push16`
//! opcodes generate true SSA assignments with versioned variables. All other
//! opcodes (arithmetic, comparisons, control flow, etc.) are lowered to
//! comment-only statements. This means the resulting [`SsaForm`] is useful for
//! structural analysis (dominance, φ placement) but does **not** yet model
//! data flow for the full Neo VM instruction set.
//!
//! Extending coverage requires mapping each opcode's stack effects to explicit
//! SSA definitions and uses.

#![allow(clippy::needless_return)]

use std::collections::{BTreeMap, BTreeSet};

use crate::decompiler::cfg::{BlockId, Cfg};
use crate::instruction::Instruction;

use super::dominance::{self, DominanceInfo};
use super::form::{SsaBlock, SsaExpr, SsaForm, SsaStmt, UseSite};
use super::variable::PhiNode;
use super::variable::SsaVariable;

/// Intermediate result from SSA block construction: (blocks, definitions, uses).
type SsaBuildResult = (
    BTreeMap<BlockId, SsaBlock>,
    BTreeMap<SsaVariable, BlockId>,
    BTreeMap<SsaVariable, BTreeSet<UseSite>>,
);

/// Builder for constructing SSA form from a CFG and instructions.
pub struct SsaBuilder<'a> {
    /// The CFG being converted to SSA.
    cfg: &'a Cfg,

    /// Instructions referenced by the CFG (indexed by offset).
    instructions: &'a [Instruction],

    /// Pre-computed dominance information.
    dominance: DominanceInfo,

    /// Current version number for each base variable name.
    versions: BTreeMap<String, usize>,

    /// Locations where φ nodes should be inserted for each variable.
    /// Maps base variable name -> set of blocks needing φ nodes.
    phi_locations: BTreeMap<String, BTreeSet<BlockId>>,
}

impl<'a> SsaBuilder<'a> {
    /// Create a new SSA builder for the given CFG and instructions.
    #[must_use]
    pub fn new(cfg: &'a Cfg, instructions: &'a [Instruction]) -> Self {
        let dominance = dominance::compute(cfg);

        Self {
            cfg,
            instructions,
            dominance,
            versions: BTreeMap::new(),
            phi_locations: BTreeMap::new(),
        }
    }

    /// Build SSA form from the CFG and instructions.
    ///
    /// This implements the two-phase SSA construction algorithm:
    /// 1. Compute φ node placement using dominance frontiers
    /// 2. Perform variable renaming via dominator tree traversal
    #[must_use]
    pub fn build(mut self) -> SsaForm {
        let (ssa_blocks, definitions, uses) = self.build_ssa_blocks();
        SsaForm {
            cfg: self.cfg.clone(),
            dominance: self.dominance,
            blocks: ssa_blocks,
            definitions,
            uses,
        }
    }

    /// Build SSA blocks by placing φ nodes and renaming variables.
    ///
    /// Returns the built blocks, definitions, and uses separately so the
    /// caller can assemble `SsaForm` without cloning `dominance`.
    fn build_ssa_blocks(&mut self) -> SsaBuildResult {
        let mut ssa_blocks = BTreeMap::new();
        let mut definitions = BTreeMap::new();
        let mut uses = BTreeMap::new();

        for block in self.cfg.blocks() {
            let mut ssa_block = SsaBlock::new();

            // Add φ nodes for this block
            for (var_name, locations) in &self.phi_locations {
                if locations.contains(&block.id) {
                    let phi_node = PhiNode::new(SsaVariable::initial(var_name.clone()));
                    ssa_block.add_phi(phi_node);
                    // Record φ node as defining a new version
                    definitions.insert(SsaVariable::initial(var_name.clone()), block.id);
                }
            }

            // Add terminator information as comment
            match &block.terminator {
                crate::decompiler::cfg::Terminator::Return => {
                    ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                        format!("return from block {:?}", block.id),
                    )));
                }
                crate::decompiler::cfg::Terminator::Jump { target } => {
                    ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                        format!("jump to {:?}", target),
                    )));
                }
                crate::decompiler::cfg::Terminator::Branch {
                    then_target,
                    else_target,
                } => {
                    ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                        format!("branch: then={:?}, else={:?}", then_target, else_target),
                    )));
                }
                crate::decompiler::cfg::Terminator::Fallthrough { target } => {
                    ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                        format!("fallthrough to {:?}", target),
                    )));
                }
                crate::decompiler::cfg::Terminator::TryEntry { .. } => {
                    ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                        "try entry".to_string(),
                    )));
                }
                crate::decompiler::cfg::Terminator::EndTry { .. } => {
                    ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                        "end try".to_string(),
                    )));
                }
                crate::decompiler::cfg::Terminator::Throw => {
                    ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                        "throw exception".to_string(),
                    )));
                }
                crate::decompiler::cfg::Terminator::Abort => {
                    ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                        "abort execution".to_string(),
                    )));
                }
                crate::decompiler::cfg::Terminator::Unknown => {
                    ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                        "unknown terminator".to_string(),
                    )));
                }
            }

            // Process instructions to populate SSA statements
            let mut statement_count = 0;
            for idx in block.instruction_range.clone() {
                if let Some(instr) = self.instructions.get(idx) {
                    if self.process_instruction_for_ssa(
                        block.id,
                        idx,
                        instr,
                        &mut ssa_block,
                        &mut definitions,
                        &mut uses,
                    ) {
                        statement_count += 1;
                    }
                }
            }

            // If no statements were added, add a placeholder comment
            if statement_count == 0 && ssa_block.phi_count() == 0 {
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    format!(
                        "empty block {:?} (offsets {}..{})",
                        block.id, block.start_offset, block.end_offset
                    ),
                )));
            }

            ssa_blocks.insert(block.id, ssa_block);
        }

        (ssa_blocks, definitions, uses)
    }

    /// Process a single instruction to extract SSA-relevant information.
    ///
    /// Returns true if an SSA statement was created.
    fn process_instruction_for_ssa(
        &mut self,
        block_id: BlockId,
        offset: usize,
        instr: &Instruction,
        ssa_block: &mut SsaBlock,
        definitions: &mut BTreeMap<SsaVariable, BlockId>,
        _uses: &mut BTreeMap<SsaVariable, BTreeSet<UseSite>>,
    ) -> bool {
        use crate::instruction::OpCode;

        // Create a comment showing the instruction
        ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
            format!("// {}: {:?}", offset, instr.opcode),
        )));

        // Track variable operations
        match instr.opcode {
            // Handle Push0-Push16 opcodes using a unified pattern
            OpCode::Push0
            | OpCode::Push1
            | OpCode::Push2
            | OpCode::Push3
            | OpCode::Push4
            | OpCode::Push5
            | OpCode::Push6
            | OpCode::Push7
            | OpCode::Push8
            | OpCode::Push9
            | OpCode::Push10
            | OpCode::Push11
            | OpCode::Push12
            | OpCode::Push13
            | OpCode::Push14
            | OpCode::Push15
            | OpCode::Push16 => {
                let value = self.extract_push_value(instr.opcode);
                let var = self.new_version(format!("stack_{}", value));
                ssa_block.add_stmt(SsaStmt::assign(
                    var.clone(),
                    SsaExpr::lit(crate::decompiler::ir::Literal::Int(value)),
                ));
                definitions.insert(var, block_id);
                return true;
            }
            OpCode::Add => {
                // Binary operation - create a dummy addition
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    "ADD operation (binary addition)".to_string(),
                )));
                return true;
            }
            OpCode::Sub => {
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    "SUB operation (binary subtraction)".to_string(),
                )));
                return true;
            }
            OpCode::Mul => {
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    "MUL operation (binary multiplication)".to_string(),
                )));
                return true;
            }
            OpCode::Div => {
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    "DIV operation (binary division)".to_string(),
                )));
                return true;
            }
            OpCode::Ret => {
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    "RET (return from function)".to_string(),
                )));
                return true;
            }
            OpCode::Nop => {
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    "NOP (no operation)".to_string(),
                )));
                return true;
            }
            OpCode::Isnull => {
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    "ISNULL (null check)".to_string(),
                )));
                return true;
            }
            OpCode::Equal => {
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    "EQUAL (equality comparison)".to_string(),
                )));
                return true;
            }
            OpCode::Notequal => {
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    "NOTEQUAL (inequality comparison)".to_string(),
                )));
                return true;
            }
            _ => {
                // For other opcodes, just add a comment
                ssa_block.add_stmt(SsaStmt::other(crate::decompiler::ir::Stmt::comment(
                    format!("{:?}", instr.opcode),
                )));
                return true;
            }
        }
    }

    /// Create a new version of a variable.
    fn new_version(&mut self, base: String) -> SsaVariable {
        let version = self.versions.entry(base.clone()).or_insert(0);
        let var = SsaVariable::new(base, *version);
        *version += 1;
        var
    }

    /// Extract the integer value from a Push0-Push16 opcode.
    fn extract_push_value(&self, opcode: crate::instruction::OpCode) -> i64 {
        use crate::instruction::OpCode;
        match opcode {
            OpCode::Push0 => 0,
            OpCode::Push1 => 1,
            OpCode::Push2 => 2,
            OpCode::Push3 => 3,
            OpCode::Push4 => 4,
            OpCode::Push5 => 5,
            OpCode::Push6 => 6,
            OpCode::Push7 => 7,
            OpCode::Push8 => 8,
            OpCode::Push9 => 9,
            OpCode::Push10 => 10,
            OpCode::Push11 => 11,
            OpCode::Push12 => 12,
            OpCode::Push13 => 13,
            OpCode::Push14 => 14,
            OpCode::Push15 => 15,
            OpCode::Push16 => 16,
            _ => 0, // Should not happen for valid push opcodes
        }
    }
}

/// Create SSA form from a CFG without an instruction stream.
///
/// Produces an SSA skeleton with empty blocks (no φ nodes or statements).
/// The resulting form is suitable for dominance queries and structural
/// analysis but contains no data-flow information.
///
/// Use [`SsaBuilder`] when instruction-level analysis is needed.
#[must_use]
pub fn build_ssa_from_cfg(cfg: &Cfg) -> SsaForm {
    let dominance = dominance::compute(cfg);
    let mut ssa_blocks = BTreeMap::new();

    for block in cfg.blocks() {
        let ssa_block = SsaBlock::new();
        ssa_blocks.insert(block.id, ssa_block);
    }

    SsaForm {
        cfg: cfg.clone(),
        dominance,
        blocks: ssa_blocks,
        definitions: BTreeMap::new(),
        uses: BTreeMap::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::decompiler::cfg::{BasicBlock, BlockId, Cfg, Terminator};

    #[test]
    fn test_builder_creation() {
        let cfg = Cfg::new();
        let instructions = &[];
        let builder = SsaBuilder::new(&cfg, instructions);

        assert_eq!(builder.versions.len(), 0);
        assert_eq!(builder.phi_locations.len(), 0);
    }

    #[test]
    fn test_new_version_increments() {
        let cfg = Cfg::new();
        let instructions = &[];
        let mut builder = SsaBuilder::new(&cfg, instructions);

        let v1 = builder.new_version("x".to_string());
        let v2 = builder.new_version("x".to_string());
        let v3 = builder.new_version("y".to_string());

        assert_eq!(v1.version, 0);
        assert_eq!(v2.version, 1);
        assert_eq!(v3.version, 0);
    }

    #[test]
    fn test_build_ssa_from_cfg() {
        let cfg = Cfg::new();
        let ssa = build_ssa_from_cfg(&cfg);

        assert_eq!(ssa.block_count(), 0);
    }

    #[test]
    fn test_build_ssa_with_blocks() {
        let mut cfg = Cfg::new();
        let block = BasicBlock::new(BlockId::ENTRY, 0, 0, 0..0, Terminator::Return);
        cfg.add_block(block);

        let ssa = build_ssa_from_cfg(&cfg);

        assert_eq!(ssa.block_count(), 1);
    }
}