(
mut function: Function,
data_types: &HashMap<String, DataType>,
)
| 250 | function.name |
| 251 | ) |
| 252 | ); |
| 253 | return; |
| 254 | } |
| 255 | breadcrumbs::log!( |
| 256 | breadcrumbs::LogLevel::Info, |
| 257 | "optimisation", |
| 258 | format!("Optimizing function: {}", function.name) |
| 259 | ); |
| 260 | |
| 261 | // 0. Run needed reorganisation passes |
| 262 | convert_labels_to_basic_blocks_in_function(function); |
| 263 | eliminate_duplicate_basic_blocks(function); |
| 264 | |
| 265 | // 1. Build Initial CFG |
| 266 | let cfg = build_cfg(&mut function.body); |
| 267 | if cfg.is_empty() { |
| 268 | breadcrumbs::log!( |
| 269 | breadcrumbs::LogLevel::Warn, |
| 270 | "optimisation", |
| 271 | format!( |
| 272 | "Warning: CFG construction failed for non-empty function {}", |
| 273 | function.name |
| 274 | ) |
| 275 | ); |
| 276 | return; |
| 277 | } |
| 278 | |
| 279 | // 2. Perform Dataflow Analysis (Constant Propagation) |
| 280 | // Ensure entry point exists in CFG before analysis |
| 281 | if !cfg.contains_key(&function.body.entry) && !cfg.is_empty() { |
| 282 | breadcrumbs::log!( |
| 283 | breadcrumbs::LogLevel::Error, |
| 284 | "optimisation", |
| 285 | format!( |
| 286 | "ERROR: Entry block '{}' not found in CFG for function {}. Skipping optimization.", |
| 287 | function.body.entry, function.name |
| 288 | ) |
| 289 | ); |
| 290 | // This might happen if the entry block itself has no instructions or references invalid blocks. |
| 291 | function.body.basic_blocks = cfg |
| 292 | .into_iter() |
| 293 | .map(|(label, info)| (label, info.original_block)) |
| 294 | .collect(); |
| 295 | return; |
| 296 | } |
| 297 | let analysis_result = analyze_constant_propagation(&function.body.entry, &cfg); |
| 298 | |
| 299 | // 3. Transform & Perform Dead Code Elimination |
| 300 | transform_function(function, &cfg, &analysis_result, data_types); |
| 301 | |
| 302 | // 4. Clean up simple copies introduced by lowering and constant/algebraic rewrites. |
| 303 | propagate_copies_and_eliminate_dead_moves(function); |
| 304 | |
| 305 | // 5. Eliminate duplicate basic blocks (re-pass-through after transformation) |
| 306 | eliminate_duplicate_basic_blocks(function); |
| 307 | |
| 308 | breadcrumbs::log!( |
| 309 | breadcrumbs::LogLevel::Info, |
no test coverage detected