diff --git a/src/mir/basic_block.rs b/src/mir/basic_block.rs index 88953c72..7db19dbf 100644 --- a/src/mir/basic_block.rs +++ b/src/mir/basic_block.rs @@ -5,7 +5,7 @@ */ use super::{EffectMask, MirInstruction, ValueId}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::fmt; /// Unique identifier for basic blocks within a function @@ -219,6 +219,24 @@ impl BasicBlock { self.instructions.insert(phi_count, instruction); } + /// Update PHI instruction input by destination ValueId + /// Used for loop back-edge PHI updates + pub fn update_phi_input( + &mut self, + phi_dst: ValueId, + incoming: (BasicBlockId, ValueId), + ) -> Result<(), String> { + for inst in &mut self.instructions { + if let MirInstruction::Phi { dst, inputs } = inst { + if *dst == phi_dst { + inputs.push(incoming); + return Ok(()); + } + } + } + Err(format!("PHI instruction with dst {:?} not found in block {:?}", phi_dst, self.id)) + } + /// Replace terminator instruction pub fn set_terminator(&mut self, terminator: MirInstruction) { if !self.is_terminator(&terminator) { diff --git a/src/mir/function.rs b/src/mir/function.rs index 5351f341..3cb79a05 100644 --- a/src/mir/function.rs +++ b/src/mir/function.rs @@ -4,7 +4,7 @@ * Functions contain basic blocks and SSA values, modules contain functions */ -use super::{BasicBlock, BasicBlockId, EffectMask, MirType, ValueId}; +use super::{BasicBlock, BasicBlockId, EffectMask, MirInstruction, MirType, ValueId}; use std::collections::HashMap; use std::fmt; @@ -249,6 +249,44 @@ impl MirFunction { is_pure: self.signature.effects.is_pure(), } } + + /// Set jump terminator if block is not already terminated + /// Helper for JSON v0 Bridge and loop lowering + pub fn set_jump_terminator( + &mut self, + bb_id: BasicBlockId, + target: BasicBlockId, + ) -> Result<(), String> { + if let Some(bb) = self.get_block_mut(bb_id) { + if !bb.is_terminated() { + bb.set_terminator(MirInstruction::Jump { target }); + } + Ok(()) + } else { + Err(format!("Block {:?} not found", bb_id)) + } + } + + /// Set branch terminator + /// Helper for JSON v0 Bridge if/else lowering + pub fn set_branch_terminator( + &mut self, + bb_id: BasicBlockId, + condition: ValueId, + then_bb: BasicBlockId, + else_bb: BasicBlockId, + ) -> Result<(), String> { + if let Some(bb) = self.get_block_mut(bb_id) { + bb.set_terminator(MirInstruction::Branch { + condition, + then_bb, + else_bb, + }); + Ok(()) + } else { + Err(format!("Block {:?} not found", bb_id)) + } + } } /// Function statistics for profiling and optimization