1 //! CLI tool to reduce Cranelift IR files crashing during compilation. 2 3 use crate::utils::read_to_string; 4 use anyhow::{Context as _, Result}; 5 use clap::Parser; 6 use cranelift::prelude::Value; 7 use cranelift_codegen::cursor::{Cursor, FuncCursor}; 8 use cranelift_codegen::flowgraph::ControlFlowGraph; 9 use cranelift_codegen::ir::types::{F32, F64, I128, I64}; 10 use cranelift_codegen::ir::{ 11 self, Block, FuncRef, Function, GlobalValueData, Inst, InstBuilder, InstructionData, 12 StackSlots, TrapCode, 13 }; 14 use cranelift_codegen::isa::TargetIsa; 15 use cranelift_codegen::Context; 16 use cranelift_entity::PrimaryMap; 17 use cranelift_reader::{parse_sets_and_triple, parse_test, ParseOptions}; 18 use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle}; 19 use std::collections::HashMap; 20 use std::path::PathBuf; 21 22 /// Reduce size of clif file causing panic during compilation. 23 #[derive(Parser)] 24 pub struct Options { 25 /// Specify an input file to be used. Use '-' for stdin. 26 file: PathBuf, 27 28 /// Configure Cranelift settings 29 #[arg(long = "set")] 30 settings: Vec<String>, 31 32 /// Specify the target architecture. 33 target: String, 34 35 /// Be more verbose 36 #[arg(short, long)] 37 verbose: bool, 38 } 39 40 pub fn run(options: &Options) -> Result<()> { 41 let parsed = parse_sets_and_triple(&options.settings, &options.target)?; 42 let fisa = parsed.as_fisa(); 43 44 let buffer = read_to_string(&options.file)?; 45 let test_file = parse_test(&buffer, ParseOptions::default()) 46 .with_context(|| format!("failed to parse {}", options.file.display()))?; 47 48 // If we have an isa from the command-line, use that. Otherwise if the 49 // file contains a unique isa, use that. 50 let isa = if let Some(isa) = fisa.isa { 51 isa 52 } else if let Some(isa) = test_file.isa_spec.unique_isa() { 53 isa 54 } else { 55 anyhow::bail!("compilation requires a target isa"); 56 }; 57 58 std::env::set_var("RUST_BACKTRACE", "0"); // Disable backtraces to reduce verbosity 59 60 for (func, _) in test_file.functions { 61 let (orig_block_count, orig_inst_count) = (block_count(&func), inst_count(&func)); 62 63 match reduce(isa, func, options.verbose) { 64 Ok((func, crash_msg)) => { 65 println!("Crash message: {}", crash_msg); 66 println!("\n{}", func); 67 println!( 68 "{} blocks {} insts -> {} blocks {} insts", 69 orig_block_count, 70 orig_inst_count, 71 block_count(&func), 72 inst_count(&func) 73 ); 74 } 75 Err(err) => println!("Warning: {}", err), 76 } 77 } 78 79 Ok(()) 80 } 81 82 enum ProgressStatus { 83 /// The mutation raised or reduced the amount of instructions or blocks. 84 ExpandedOrShrinked, 85 86 /// The mutation only changed an instruction. Performing another round of mutations may only 87 /// reduce the test case if another mutation shrank the test case. 88 Changed, 89 90 /// No need to re-test if the program crashes, because the mutation had no effect, but we want 91 /// to keep on iterating. 92 Skip, 93 } 94 95 trait Mutator { 96 fn name(&self) -> &'static str; 97 fn mutation_count(&self, func: &Function) -> usize; 98 fn mutate(&mut self, func: Function) -> Option<(Function, String, ProgressStatus)>; 99 100 /// Gets called when the returned mutated function kept on causing the crash. This can be used 101 /// to update position of the next item to look at. Does nothing by default. 102 fn did_crash(&mut self) {} 103 } 104 105 /// Try to remove instructions. 106 struct RemoveInst { 107 block: Block, 108 inst: Inst, 109 } 110 111 impl RemoveInst { 112 fn new(func: &Function) -> Self { 113 let first_block = func.layout.entry_block().unwrap(); 114 let first_inst = func.layout.first_inst(first_block).unwrap(); 115 Self { 116 block: first_block, 117 inst: first_inst, 118 } 119 } 120 } 121 122 impl Mutator for RemoveInst { 123 fn name(&self) -> &'static str { 124 "remove inst" 125 } 126 127 fn mutation_count(&self, func: &Function) -> usize { 128 inst_count(func) 129 } 130 131 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 132 next_inst_ret_prev(&func, &mut self.block, &mut self.inst).map(|(prev_block, prev_inst)| { 133 func.layout.remove_inst(prev_inst); 134 let msg = if func.layout.block_insts(prev_block).next().is_none() { 135 // Make sure empty blocks are removed, as `next_inst_ret_prev` depends on non empty blocks 136 func.layout.remove_block(prev_block); 137 format!("Remove inst {} and empty block {}", prev_inst, prev_block) 138 } else { 139 format!("Remove inst {}", prev_inst) 140 }; 141 (func, msg, ProgressStatus::ExpandedOrShrinked) 142 }) 143 } 144 } 145 146 /// Try to replace instructions with `iconst` or `fconst`. 147 struct ReplaceInstWithConst { 148 block: Block, 149 inst: Inst, 150 } 151 152 impl ReplaceInstWithConst { 153 fn new(func: &Function) -> Self { 154 let first_block = func.layout.entry_block().unwrap(); 155 let first_inst = func.layout.first_inst(first_block).unwrap(); 156 Self { 157 block: first_block, 158 inst: first_inst, 159 } 160 } 161 } 162 163 impl Mutator for ReplaceInstWithConst { 164 fn name(&self) -> &'static str { 165 "replace inst with const" 166 } 167 168 fn mutation_count(&self, func: &Function) -> usize { 169 inst_count(func) 170 } 171 172 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 173 next_inst_ret_prev(&func, &mut self.block, &mut self.inst).map( 174 |(_prev_block, prev_inst)| { 175 let num_results = func.dfg.inst_results(prev_inst).len(); 176 177 let opcode = func.dfg.insts[prev_inst].opcode(); 178 if num_results == 0 179 || opcode == ir::Opcode::Iconst 180 || opcode == ir::Opcode::F32const 181 || opcode == ir::Opcode::F64const 182 { 183 return (func, format!(""), ProgressStatus::Skip); 184 } 185 186 // We replace a i128 const with a uextend+iconst, so we need to match that here 187 // to avoid processing those multiple times 188 if opcode == ir::Opcode::Uextend { 189 let ret_ty = func.dfg.value_type(func.dfg.first_result(prev_inst)); 190 let is_uextend_i128 = ret_ty == I128; 191 192 let arg = func.dfg.inst_args(prev_inst)[0]; 193 let arg_def = func.dfg.value_def(arg); 194 let arg_is_iconst = arg_def 195 .inst() 196 .map(|inst| func.dfg.insts[inst].opcode() == ir::Opcode::Iconst) 197 .unwrap_or(false); 198 199 if is_uextend_i128 && arg_is_iconst { 200 return (func, format!(""), ProgressStatus::Skip); 201 } 202 } 203 204 // At least 2 results. Replace each instruction with as many const instructions as 205 // there are results. 206 let mut pos = FuncCursor::new(&mut func).at_inst(prev_inst); 207 208 // Copy result SSA names into our own vector; otherwise we couldn't mutably borrow pos 209 // in the loop below. 210 let results = pos.func.dfg.inst_results(prev_inst).to_vec(); 211 212 // Detach results from the previous instruction, since we're going to reuse them. 213 pos.func.dfg.clear_results(prev_inst); 214 215 let mut inst_names = Vec::new(); 216 for r in &results { 217 let new_inst_name = replace_with_const(&mut pos, *r); 218 inst_names.push(new_inst_name); 219 } 220 221 // Remove the instruction. 222 assert_eq!(pos.remove_inst(), prev_inst); 223 224 let progress = if results.len() == 1 { 225 ProgressStatus::Changed 226 } else { 227 ProgressStatus::ExpandedOrShrinked 228 }; 229 230 ( 231 func, 232 format!("Replace inst {} with {}", prev_inst, inst_names.join(" / ")), 233 progress, 234 ) 235 }, 236 ) 237 } 238 } 239 240 /// Try to replace instructions with `trap`. 241 struct ReplaceInstWithTrap { 242 block: Block, 243 inst: Inst, 244 } 245 246 impl ReplaceInstWithTrap { 247 fn new(func: &Function) -> Self { 248 let first_block = func.layout.entry_block().unwrap(); 249 let first_inst = func.layout.first_inst(first_block).unwrap(); 250 Self { 251 block: first_block, 252 inst: first_inst, 253 } 254 } 255 } 256 257 impl Mutator for ReplaceInstWithTrap { 258 fn name(&self) -> &'static str { 259 "replace inst with trap" 260 } 261 262 fn mutation_count(&self, func: &Function) -> usize { 263 inst_count(func) 264 } 265 266 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 267 next_inst_ret_prev(&func, &mut self.block, &mut self.inst).map( 268 |(_prev_block, prev_inst)| { 269 let status = if func.dfg.insts[prev_inst].opcode() == ir::Opcode::Trap { 270 ProgressStatus::Skip 271 } else { 272 func.dfg.replace(prev_inst).trap(TrapCode::User(0)); 273 ProgressStatus::Changed 274 }; 275 ( 276 func, 277 format!("Replace inst {} with trap", prev_inst), 278 status, 279 ) 280 }, 281 ) 282 } 283 } 284 285 /// Try to move instructions to entry block. 286 struct MoveInstToEntryBlock { 287 block: Block, 288 inst: Inst, 289 } 290 291 impl MoveInstToEntryBlock { 292 fn new(func: &Function) -> Self { 293 let first_block = func.layout.entry_block().unwrap(); 294 let first_inst = func.layout.first_inst(first_block).unwrap(); 295 Self { 296 block: first_block, 297 inst: first_inst, 298 } 299 } 300 } 301 302 impl Mutator for MoveInstToEntryBlock { 303 fn name(&self) -> &'static str { 304 "move inst to entry block" 305 } 306 307 fn mutation_count(&self, func: &Function) -> usize { 308 inst_count(func) 309 } 310 311 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 312 next_inst_ret_prev(&func, &mut self.block, &mut self.inst).map(|(prev_block, prev_inst)| { 313 // Don't move instructions that are already in entry block 314 // and instructions that end blocks. 315 let first_block = func.layout.entry_block().unwrap(); 316 if first_block == prev_block || self.block != prev_block { 317 return ( 318 func, 319 format!("did nothing for {}", prev_inst), 320 ProgressStatus::Skip, 321 ); 322 } 323 324 let last_inst_of_first_block = func.layout.last_inst(first_block).unwrap(); 325 func.layout.remove_inst(prev_inst); 326 func.layout.insert_inst(prev_inst, last_inst_of_first_block); 327 328 ( 329 func, 330 format!("Move inst {} to entry block", prev_inst), 331 ProgressStatus::ExpandedOrShrinked, 332 ) 333 }) 334 } 335 } 336 337 /// Try to remove a block. 338 struct RemoveBlock { 339 block: Block, 340 } 341 342 impl RemoveBlock { 343 fn new(func: &Function) -> Self { 344 Self { 345 block: func.layout.entry_block().unwrap(), 346 } 347 } 348 } 349 350 impl Mutator for RemoveBlock { 351 fn name(&self) -> &'static str { 352 "remove block" 353 } 354 355 fn mutation_count(&self, func: &Function) -> usize { 356 block_count(func) 357 } 358 359 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 360 func.layout.next_block(self.block).map(|next_block| { 361 self.block = next_block; 362 while let Some(inst) = func.layout.last_inst(self.block) { 363 func.layout.remove_inst(inst); 364 } 365 func.layout.remove_block(self.block); 366 ( 367 func, 368 format!("Remove block {}", next_block), 369 ProgressStatus::ExpandedOrShrinked, 370 ) 371 }) 372 } 373 } 374 375 /// Try to replace the block params with constants. 376 struct ReplaceBlockParamWithConst { 377 block: Block, 378 params_remaining: usize, 379 } 380 381 impl ReplaceBlockParamWithConst { 382 fn new(func: &Function) -> Self { 383 let first_block = func.layout.entry_block().unwrap(); 384 Self { 385 block: first_block, 386 params_remaining: func.dfg.num_block_params(first_block), 387 } 388 } 389 } 390 391 impl Mutator for ReplaceBlockParamWithConst { 392 fn name(&self) -> &'static str { 393 "replace block parameter with const" 394 } 395 396 fn mutation_count(&self, func: &Function) -> usize { 397 func.layout 398 .blocks() 399 .map(|block| func.dfg.num_block_params(block)) 400 .sum() 401 } 402 403 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 404 while self.params_remaining == 0 { 405 self.block = func.layout.next_block(self.block)?; 406 self.params_remaining = func.dfg.num_block_params(self.block); 407 } 408 409 self.params_remaining -= 1; 410 let param_index = self.params_remaining; 411 412 let param = func.dfg.block_params(self.block)[param_index]; 413 func.dfg.remove_block_param(param); 414 415 let first_inst = func.layout.first_inst(self.block).unwrap(); 416 let mut pos = FuncCursor::new(&mut func).at_inst(first_inst); 417 let new_inst_name = replace_with_const(&mut pos, param); 418 419 let mut cfg = ControlFlowGraph::new(); 420 cfg.compute(&func); 421 422 // Remove parameters in branching instructions that point to this block 423 for pred in cfg.pred_iter(self.block) { 424 let dfg = &mut func.dfg; 425 for branch in dfg.insts[pred.inst].branch_destination_mut(&mut dfg.jump_tables) { 426 if branch.block(&dfg.value_lists) == self.block { 427 branch.remove(param_index, &mut dfg.value_lists); 428 } 429 } 430 } 431 432 if Some(self.block) == func.layout.entry_block() { 433 // Entry block params must match function params 434 func.signature.params.remove(param_index); 435 } 436 437 Some(( 438 func, 439 format!( 440 "Replaced param {} of {} by {}", 441 param, self.block, new_inst_name 442 ), 443 ProgressStatus::ExpandedOrShrinked, 444 )) 445 } 446 } 447 448 /// Try to remove unused entities. 449 struct RemoveUnusedEntities { 450 kind: u32, 451 } 452 453 impl RemoveUnusedEntities { 454 fn new() -> Self { 455 Self { kind: 0 } 456 } 457 } 458 459 impl Mutator for RemoveUnusedEntities { 460 fn name(&self) -> &'static str { 461 "remove unused entities" 462 } 463 464 fn mutation_count(&self, _func: &Function) -> usize { 465 4 466 } 467 468 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 469 let name = match self.kind { 470 0 => { 471 let mut ext_func_usage_map = HashMap::new(); 472 for block in func.layout.blocks() { 473 for inst in func.layout.block_insts(block) { 474 match func.dfg.insts[inst] { 475 // Add new cases when there are new instruction formats taking a `FuncRef`. 476 InstructionData::Call { func_ref, .. } 477 | InstructionData::FuncAddr { func_ref, .. } => { 478 ext_func_usage_map 479 .entry(func_ref) 480 .or_insert_with(Vec::new) 481 .push(inst); 482 } 483 _ => {} 484 } 485 } 486 } 487 488 let mut ext_funcs = PrimaryMap::new(); 489 490 for (func_ref, ext_func_data) in func.dfg.ext_funcs.clone().into_iter() { 491 if let Some(func_ref_usage) = ext_func_usage_map.get(&func_ref) { 492 let new_func_ref = ext_funcs.push(ext_func_data.clone()); 493 for &inst in func_ref_usage { 494 match func.dfg.insts[inst] { 495 // Keep in sync with the above match. 496 InstructionData::Call { 497 ref mut func_ref, .. 498 } 499 | InstructionData::FuncAddr { 500 ref mut func_ref, .. 501 } => { 502 *func_ref = new_func_ref; 503 } 504 _ => unreachable!(), 505 } 506 } 507 } 508 } 509 510 func.dfg.ext_funcs = ext_funcs; 511 512 "Remove unused ext funcs" 513 } 514 1 => { 515 #[derive(Copy, Clone)] 516 enum SigRefUser { 517 Instruction(Inst), 518 ExtFunc(FuncRef), 519 } 520 521 let mut signatures_usage_map = HashMap::new(); 522 for block in func.layout.blocks() { 523 for inst in func.layout.block_insts(block) { 524 // Add new cases when there are new instruction formats taking a `SigRef`. 525 if let InstructionData::CallIndirect { sig_ref, .. } = func.dfg.insts[inst] 526 { 527 signatures_usage_map 528 .entry(sig_ref) 529 .or_insert_with(Vec::new) 530 .push(SigRefUser::Instruction(inst)); 531 } 532 } 533 } 534 for (func_ref, ext_func_data) in func.dfg.ext_funcs.iter() { 535 signatures_usage_map 536 .entry(ext_func_data.signature) 537 .or_insert_with(Vec::new) 538 .push(SigRefUser::ExtFunc(func_ref)); 539 } 540 541 let mut signatures = PrimaryMap::new(); 542 543 for (sig_ref, sig_data) in func.dfg.signatures.clone().into_iter() { 544 if let Some(sig_ref_usage) = signatures_usage_map.get(&sig_ref) { 545 let new_sig_ref = signatures.push(sig_data.clone()); 546 for &sig_ref_user in sig_ref_usage { 547 match sig_ref_user { 548 SigRefUser::Instruction(inst) => match func.dfg.insts[inst] { 549 // Keep in sync with the above match. 550 InstructionData::CallIndirect { 551 ref mut sig_ref, .. 552 } => { 553 *sig_ref = new_sig_ref; 554 } 555 _ => unreachable!(), 556 }, 557 SigRefUser::ExtFunc(func_ref) => { 558 func.dfg.ext_funcs[func_ref].signature = new_sig_ref; 559 } 560 } 561 } 562 } 563 } 564 565 func.dfg.signatures = signatures; 566 567 "Remove unused signatures" 568 } 569 2 => { 570 let mut stack_slot_usage_map = HashMap::new(); 571 for block in func.layout.blocks() { 572 for inst in func.layout.block_insts(block) { 573 match func.dfg.insts[inst] { 574 // Add new cases when there are new instruction formats taking a `StackSlot`. 575 InstructionData::StackLoad { stack_slot, .. } 576 | InstructionData::StackStore { stack_slot, .. } => { 577 stack_slot_usage_map 578 .entry(stack_slot) 579 .or_insert_with(Vec::new) 580 .push(inst); 581 } 582 583 _ => {} 584 } 585 } 586 } 587 588 let mut stack_slots = StackSlots::new(); 589 590 for (stack_slot, stack_slot_data) in func.sized_stack_slots.clone().iter() { 591 if let Some(stack_slot_usage) = stack_slot_usage_map.get(&stack_slot) { 592 let new_stack_slot = stack_slots.push(stack_slot_data.clone()); 593 for &inst in stack_slot_usage { 594 match &mut func.dfg.insts[inst] { 595 // Keep in sync with the above match. 596 InstructionData::StackLoad { stack_slot, .. } 597 | InstructionData::StackStore { stack_slot, .. } => { 598 *stack_slot = new_stack_slot; 599 } 600 _ => unreachable!(), 601 } 602 } 603 } 604 } 605 606 func.sized_stack_slots = stack_slots; 607 608 "Remove unused stack slots" 609 } 610 3 => { 611 let mut global_value_usage_map = HashMap::new(); 612 for block in func.layout.blocks() { 613 for inst in func.layout.block_insts(block) { 614 // Add new cases when there are new instruction formats taking a `GlobalValue`. 615 if let InstructionData::UnaryGlobalValue { global_value, .. } = 616 func.dfg.insts[inst] 617 { 618 global_value_usage_map 619 .entry(global_value) 620 .or_insert_with(Vec::new) 621 .push(inst); 622 } 623 } 624 } 625 626 for (_global_value, global_value_data) in func.global_values.iter() { 627 match *global_value_data { 628 GlobalValueData::VMContext | GlobalValueData::Symbol { .. } => {} 629 // These can create cyclic references, which cause complications. Just skip 630 // the global value removal for now. 631 // FIXME Handle them in a better way. 632 GlobalValueData::Load { .. } 633 | GlobalValueData::IAddImm { .. } 634 | GlobalValueData::DynScaleTargetConst { .. } => return None, 635 } 636 } 637 638 let mut global_values = PrimaryMap::new(); 639 640 for (global_value, global_value_data) in func.global_values.clone().into_iter() { 641 if let Some(global_value_usage) = global_value_usage_map.get(&global_value) { 642 let new_global_value = global_values.push(global_value_data.clone()); 643 for &inst in global_value_usage { 644 match &mut func.dfg.insts[inst] { 645 // Keep in sync with the above match. 646 InstructionData::UnaryGlobalValue { global_value, .. } => { 647 *global_value = new_global_value; 648 } 649 _ => unreachable!(), 650 } 651 } 652 } 653 } 654 655 func.global_values = global_values; 656 657 "Remove unused global values" 658 } 659 _ => return None, 660 }; 661 self.kind += 1; 662 Some((func, name.to_owned(), ProgressStatus::Changed)) 663 } 664 } 665 666 struct MergeBlocks { 667 block: Block, 668 prev_block: Option<Block>, 669 } 670 671 impl MergeBlocks { 672 fn new(func: &Function) -> Self { 673 Self { 674 block: func.layout.entry_block().unwrap(), 675 prev_block: None, 676 } 677 } 678 } 679 680 impl Mutator for MergeBlocks { 681 fn name(&self) -> &'static str { 682 "merge blocks" 683 } 684 685 fn mutation_count(&self, func: &Function) -> usize { 686 // N blocks may result in at most N-1 merges. 687 block_count(func) - 1 688 } 689 690 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 691 let block = match func.layout.next_block(self.block) { 692 Some(block) => block, 693 None => return None, 694 }; 695 696 self.block = block; 697 698 let mut cfg = ControlFlowGraph::new(); 699 cfg.compute(&func); 700 701 if cfg.pred_iter(block).count() != 1 { 702 return Some(( 703 func, 704 format!("did nothing for {}", block), 705 ProgressStatus::Skip, 706 )); 707 } 708 709 let pred = cfg.pred_iter(block).next().unwrap(); 710 711 // If the branch instruction that lead us to this block wasn't an unconditional jump, then 712 // we have a conditional jump sequence that we should not break. 713 let branch_dests = func.dfg.insts[pred.inst].branch_destination(&func.dfg.jump_tables); 714 if branch_dests.len() != 1 { 715 return Some(( 716 func, 717 format!("did nothing for {}", block), 718 ProgressStatus::Skip, 719 )); 720 } 721 722 let branch_args = branch_dests[0].args_slice(&func.dfg.value_lists).to_vec(); 723 724 // TODO: should we free the entity list associated with the block params? 725 let block_params = func 726 .dfg 727 .detach_block_params(block) 728 .as_slice(&func.dfg.value_lists) 729 .to_vec(); 730 731 assert_eq!(block_params.len(), branch_args.len()); 732 733 // If there were any block parameters in block, then the last instruction in pred will 734 // fill these parameters. Make the block params aliases of the terminator arguments. 735 for (block_param, arg) in block_params.into_iter().zip(branch_args) { 736 if block_param != arg { 737 func.dfg.change_to_alias(block_param, arg); 738 } 739 } 740 741 // Remove the terminator branch to the current block. 742 func.layout.remove_inst(pred.inst); 743 744 // Move all the instructions to the predecessor. 745 while let Some(inst) = func.layout.first_inst(block) { 746 func.layout.remove_inst(inst); 747 func.layout.append_inst(inst, pred.block); 748 } 749 750 // Remove the predecessor block. 751 func.layout.remove_block(block); 752 753 // Record the previous block: if we caused a crash (as signaled by a call to did_crash), then 754 // we'll start back to this block. 755 self.prev_block = Some(pred.block); 756 757 Some(( 758 func, 759 format!("merged {} and {}", pred.block, block), 760 ProgressStatus::ExpandedOrShrinked, 761 )) 762 } 763 764 fn did_crash(&mut self) { 765 self.block = self.prev_block.unwrap(); 766 } 767 } 768 769 fn replace_with_const(pos: &mut FuncCursor, param: Value) -> &'static str { 770 let ty = pos.func.dfg.value_type(param); 771 if ty == F32 { 772 pos.ins().with_result(param).f32const(0.0); 773 "f32const" 774 } else if ty == F64 { 775 pos.ins().with_result(param).f64const(0.0); 776 "f64const" 777 } else if ty.is_ref() { 778 pos.ins().with_result(param).null(ty); 779 "null" 780 } else if ty.is_vector() { 781 let zero_data = vec![0; ty.bytes() as usize].into(); 782 let zero_handle = pos.func.dfg.constants.insert(zero_data); 783 pos.ins().with_result(param).vconst(ty, zero_handle); 784 "vconst" 785 } else if ty == I128 { 786 let res = pos.ins().iconst(I64, 0); 787 pos.ins().with_result(param).uextend(I128, res); 788 "iconst+uextend" 789 } else { 790 // Default to an integer type and possibly create verifier error 791 pos.ins().with_result(param).iconst(ty, 0); 792 "iconst" 793 } 794 } 795 796 fn next_inst_ret_prev( 797 func: &Function, 798 block: &mut Block, 799 inst: &mut Inst, 800 ) -> Option<(Block, Inst)> { 801 let prev = (*block, *inst); 802 if let Some(next_inst) = func.layout.next_inst(*inst) { 803 *inst = next_inst; 804 return Some(prev); 805 } 806 if let Some(next_block) = func.layout.next_block(*block) { 807 *block = next_block; 808 *inst = func.layout.first_inst(*block).expect("no inst"); 809 return Some(prev); 810 } 811 None 812 } 813 814 fn block_count(func: &Function) -> usize { 815 func.layout.blocks().count() 816 } 817 818 fn inst_count(func: &Function) -> usize { 819 func.layout 820 .blocks() 821 .map(|block| func.layout.block_insts(block).count()) 822 .sum() 823 } 824 825 /// Resolve aliases only if function still crashes after this. 826 fn try_resolve_aliases(context: &mut CrashCheckContext, func: &mut Function) { 827 let mut func_with_resolved_aliases = func.clone(); 828 func_with_resolved_aliases.dfg.resolve_all_aliases(); 829 if let CheckResult::Crash(_) = context.check_for_crash(&func_with_resolved_aliases) { 830 *func = func_with_resolved_aliases; 831 } 832 } 833 834 fn reduce(isa: &dyn TargetIsa, mut func: Function, verbose: bool) -> Result<(Function, String)> { 835 let mut context = CrashCheckContext::new(isa); 836 837 if let CheckResult::Succeed = context.check_for_crash(&func) { 838 anyhow::bail!("Given function compiled successfully or gave a verifier error."); 839 } 840 841 try_resolve_aliases(&mut context, &mut func); 842 843 let progress_bar = ProgressBar::with_draw_target(0, ProgressDrawTarget::stdout()); 844 progress_bar.set_style( 845 ProgressStyle::default_bar().template("{bar:60} {prefix:40} {pos:>4}/{len:>4} {msg}"), 846 ); 847 848 for pass_idx in 0..100 { 849 let mut should_keep_reducing = false; 850 let mut phase = 0; 851 852 loop { 853 let mut mutator: Box<dyn Mutator> = match phase { 854 0 => Box::new(RemoveInst::new(&func)), 855 1 => Box::new(ReplaceInstWithConst::new(&func)), 856 2 => Box::new(ReplaceInstWithTrap::new(&func)), 857 3 => Box::new(MoveInstToEntryBlock::new(&func)), 858 4 => Box::new(RemoveBlock::new(&func)), 859 5 => Box::new(ReplaceBlockParamWithConst::new(&func)), 860 6 => Box::new(RemoveUnusedEntities::new()), 861 7 => Box::new(MergeBlocks::new(&func)), 862 _ => break, 863 }; 864 865 progress_bar.set_prefix(&format!("pass {} phase {}", pass_idx, mutator.name())); 866 progress_bar.set_length(mutator.mutation_count(&func) as u64); 867 868 // Reset progress bar. 869 progress_bar.set_position(0); 870 progress_bar.set_draw_delta(0); 871 872 for _ in 0..10000 { 873 progress_bar.inc(1); 874 875 let (mutated_func, msg, mutation_kind) = match mutator.mutate(func.clone()) { 876 Some(res) => res, 877 None => { 878 break; 879 } 880 }; 881 882 if let ProgressStatus::Skip = mutation_kind { 883 // The mutator didn't change anything, but we want to try more mutator 884 // iterations. 885 continue; 886 } 887 888 progress_bar.set_message(&msg); 889 890 match context.check_for_crash(&mutated_func) { 891 CheckResult::Succeed => { 892 // Mutating didn't hit the problem anymore, discard changes. 893 continue; 894 } 895 CheckResult::Crash(_) => { 896 // Panic remained while mutating, make changes definitive. 897 func = mutated_func; 898 899 // Notify the mutator that the mutation was successful. 900 mutator.did_crash(); 901 902 let verb = match mutation_kind { 903 ProgressStatus::ExpandedOrShrinked => { 904 should_keep_reducing = true; 905 "shrink" 906 } 907 ProgressStatus::Changed => "changed", 908 ProgressStatus::Skip => unreachable!(), 909 }; 910 if verbose { 911 progress_bar.println(format!("{}: {}", msg, verb)); 912 } 913 } 914 } 915 } 916 917 phase += 1; 918 } 919 920 progress_bar.println(format!( 921 "After pass {}, remaining insts/blocks: {}/{} ({})", 922 pass_idx, 923 inst_count(&func), 924 block_count(&func), 925 if should_keep_reducing { 926 "will keep reducing" 927 } else { 928 "stop reducing" 929 } 930 )); 931 932 if !should_keep_reducing { 933 // No new shrinking opportunities have been found this pass. This means none will ever 934 // be found. Skip the rest of the passes over the function. 935 break; 936 } 937 } 938 939 try_resolve_aliases(&mut context, &mut func); 940 progress_bar.finish(); 941 942 let crash_msg = match context.check_for_crash(&func) { 943 CheckResult::Succeed => unreachable!("Used to crash, but doesn't anymore???"), 944 CheckResult::Crash(crash_msg) => crash_msg, 945 }; 946 947 Ok((func, crash_msg)) 948 } 949 950 struct CrashCheckContext<'a> { 951 /// Cached `Context`, to prevent repeated allocation. 952 context: Context, 953 954 /// Cached code memory, to prevent repeated allocation. 955 code_memory: Vec<u8>, 956 957 /// The target isa to compile for. 958 isa: &'a dyn TargetIsa, 959 } 960 961 fn get_panic_string(panic: Box<dyn std::any::Any>) -> String { 962 let panic = match panic.downcast::<&'static str>() { 963 Ok(panic_msg) => { 964 return panic_msg.to_string(); 965 } 966 Err(panic) => panic, 967 }; 968 match panic.downcast::<String>() { 969 Ok(panic_msg) => *panic_msg, 970 Err(_) => "Box<Any>".to_string(), 971 } 972 } 973 974 enum CheckResult { 975 /// The function compiled fine, or the verifier noticed an error. 976 Succeed, 977 978 /// The compilation of the function panicked. 979 Crash(String), 980 } 981 982 impl<'a> CrashCheckContext<'a> { 983 fn new(isa: &'a dyn TargetIsa) -> Self { 984 CrashCheckContext { 985 context: Context::new(), 986 code_memory: Vec::new(), 987 isa, 988 } 989 } 990 991 #[cfg_attr(test, allow(unreachable_code))] 992 fn check_for_crash(&mut self, func: &Function) -> CheckResult { 993 self.context.clear(); 994 self.code_memory.clear(); 995 996 self.context.func = func.clone(); 997 998 use std::io::Write; 999 std::io::stdout().flush().unwrap(); // Flush stdout to sync with panic messages on stderr 1000 1001 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { 1002 cranelift_codegen::verifier::verify_function(&func, self.isa).err() 1003 })) { 1004 Ok(Some(_)) => return CheckResult::Succeed, 1005 Ok(None) => {} 1006 // The verifier panicked. Compiling it will probably give the same panic. 1007 // We treat it as succeeding to make it possible to reduce for the actual error. 1008 // FIXME prevent verifier panic on removing block0. 1009 Err(_) => return CheckResult::Succeed, 1010 } 1011 1012 #[cfg(test)] 1013 { 1014 // For testing purposes we emulate a panic caused by the existence of 1015 // a `call` instruction. 1016 let contains_call = func.layout.blocks().any(|block| { 1017 func.layout 1018 .block_insts(block) 1019 .any(|inst| match func.dfg.insts[inst] { 1020 InstructionData::Call { .. } => true, 1021 _ => false, 1022 }) 1023 }); 1024 if contains_call { 1025 return CheckResult::Crash("test crash".to_string()); 1026 } else { 1027 return CheckResult::Succeed; 1028 } 1029 } 1030 1031 let old_panic_hook = std::panic::take_hook(); 1032 std::panic::set_hook(Box::new(|_| {})); // silence panics 1033 1034 let res = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { 1035 let _ = self.context.compile_and_emit( 1036 self.isa, 1037 &mut self.code_memory, 1038 &mut Default::default(), 1039 ); 1040 })) { 1041 Ok(()) => CheckResult::Succeed, 1042 Err(err) => CheckResult::Crash(get_panic_string(err)), 1043 }; 1044 1045 std::panic::set_hook(old_panic_hook); 1046 1047 res 1048 } 1049 } 1050 1051 #[cfg(test)] 1052 mod tests { 1053 use super::*; 1054 1055 fn run_test(test_str: &str, expected_str: &str) { 1056 let test_file = parse_test(test_str, ParseOptions::default()).unwrap(); 1057 1058 // If we have an isa from the command-line, use that. Otherwise if the 1059 // file contains a unique isa, use that. 1060 let isa = test_file.isa_spec.unique_isa().expect("Unknown isa"); 1061 1062 for (func, _) in test_file.functions { 1063 let (reduced_func, crash_msg) = 1064 reduce(isa, func, false).expect("Couldn't reduce test case"); 1065 assert_eq!(crash_msg, "test crash"); 1066 1067 let (func_reduced_twice, crash_msg) = 1068 reduce(isa, reduced_func.clone(), false).expect("Couldn't re-reduce test case"); 1069 assert_eq!(crash_msg, "test crash"); 1070 1071 assert_eq!( 1072 block_count(&func_reduced_twice), 1073 block_count(&reduced_func), 1074 "reduction wasn't maximal for blocks" 1075 ); 1076 assert_eq!( 1077 inst_count(&func_reduced_twice), 1078 inst_count(&reduced_func), 1079 "reduction wasn't maximal for insts" 1080 ); 1081 1082 let actual_ir = format!("{}", reduced_func); 1083 let expected_ir = expected_str.replace("\r\n", "\n"); 1084 assert!( 1085 expected_ir == actual_ir, 1086 "Expected:\n{}\nGot:\n{}", 1087 expected_ir, 1088 actual_ir, 1089 ); 1090 } 1091 } 1092 1093 #[test] 1094 fn test_reduce() { 1095 const TEST: &str = include_str!("../tests/bugpoint_test.clif"); 1096 const EXPECTED: &str = include_str!("../tests/bugpoint_test_expected.clif"); 1097 run_test(TEST, EXPECTED); 1098 } 1099 1100 #[test] 1101 fn test_consts() { 1102 const TEST: &str = include_str!("../tests/bugpoint_consts.clif"); 1103 const EXPECTED: &str = include_str!("../tests/bugpoint_consts_expected.clif"); 1104 run_test(TEST, EXPECTED); 1105 } 1106 } 1107