dotscope 0.7.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
//! Small method inlining pass.
//!
//! This pass inlines small, pure methods at their call sites. It is particularly
//! effective for:
//!
//! - Simple getters/setters
//! - Constant-returning methods
//! - String decryptor helpers
//!
//! # Inlining Criteria
//!
//! A method is considered for inlining if:
//! 1. It's small enough (instruction count <= threshold)
//! 2. It's pure or read-only (no global side effects)
//! 3. It doesn't recurse (directly or indirectly)
//! 4. The call is non-virtual (single target)
//! 5. The callee SSA is available in the context
//!
//! # Safety
//!
//! Inlining preserves semantics by:
//! - Only inlining pure/read-only methods
//! - Properly remapping all variable IDs
//! - Handling parameter binding correctly
//! - Replacing return with assignment to destination
//!
//! # Related Passes
//!
//! Proxy devirtualization and no-op elimination are handled by the standalone
//! [`ProxyDevirtualizationPass`](super::ProxyDevirtualizationPass) which runs
//! in the normalize phase unconditionally.

use std::collections::BTreeMap;

use crate::{
    analysis::{
        DefSite, ReturnInfo, SsaFunction, SsaInstruction, SsaOp, SsaType, SsaVarId, VariableOrigin,
    },
    compiler::{
        pass::{PassCapability, SsaPass},
        CompilerContext, EventKind, EventLog,
    },
    metadata::{tables::MemberRefSignature, token::Token, typesystem::CilTypeReference},
    CilObject, Result,
};

/// A candidate call site for inlining.
#[derive(Debug, Clone)]
struct InlineCandidate {
    /// Block index containing the call
    block_idx: usize,
    /// Instruction index within the block
    instr_idx: usize,
    /// Token of the method being called
    callee_token: Token,
}

/// Method-specific context for inlining operations.
///
/// This struct holds all the common parameters needed during inlining of a single
/// method, reducing parameter passing overhead and making the code cleaner.
struct InliningContext<'a> {
    /// Reference to the pass configuration (for thresholds, etc.)
    pass: &'a InliningPass,
    /// The caller's SSA being modified
    caller_ssa: &'a mut SsaFunction,
    /// Token of the method being processed
    caller_token: Token,
    /// The analysis context with method summaries, call graph, etc.
    analysis_ctx: &'a CompilerContext,
    /// The assembly for resolving tokens
    assembly: &'a CilObject,
    /// Event log for recording changes
    changes: EventLog,
}

impl<'a> InliningContext<'a> {
    /// Creates a new inlining context for processing a method.
    ///
    /// The context holds all the state needed for inlining operations on a single
    /// method, reducing parameter passing overhead in helper methods.
    ///
    /// # Arguments
    ///
    /// * `pass` - Reference to the inlining pass configuration.
    /// * `caller_ssa` - Mutable reference to the caller's SSA being modified.
    /// * `caller_token` - Token identifying the method being processed.
    /// * `analysis_ctx` - Analysis context with method summaries and call graph.
    /// * `assembly` - Assembly for resolving tokens.
    fn new(
        pass: &'a InliningPass,
        caller_ssa: &'a mut SsaFunction,
        caller_token: Token,
        analysis_ctx: &'a CompilerContext,
        assembly: &'a CilObject,
    ) -> Self {
        Self {
            pass,
            caller_ssa,
            caller_token,
            analysis_ctx,
            assembly,
            changes: EventLog::new(),
        }
    }

    /// Returns whether any changes were made during inlining.
    ///
    /// # Returns
    ///
    /// `true` if at least one inlining operation was performed.
    fn has_changes(&self) -> bool {
        !self.changes.is_empty()
    }

    /// Consumes the context and returns the accumulated event log.
    ///
    /// # Returns
    ///
    /// The event log containing all recorded changes from inlining operations.
    fn into_changes(self) -> EventLog {
        self.changes
    }

    /// Checks if a callee is a valid target for inlining.
    ///
    /// A method is invalid for inlining if it:
    /// - Is the same as the caller (self-recursion)
    /// - Is a registered decryptor (handled by decryption passes)
    /// - Is a registered dispatcher (control flow dispatcher)
    ///
    /// # Arguments
    ///
    /// * `callee_token` - Token of the method being considered for inlining.
    ///
    /// # Returns
    ///
    /// `true` if the callee can potentially be inlined.
    fn is_valid_target(&self, callee_token: Token) -> bool {
        // Don't inline self-recursion
        if callee_token == self.caller_token {
            return false;
        }

        // Check if this method should not be inlined (decryptors, dispatchers, etc.)
        if self.analysis_ctx.no_inline.contains(&callee_token) {
            return false;
        }

        true
    }

    /// Checks if a method should be fully inlined at a call site.
    ///
    /// A method qualifies for full inlining if it:
    /// - Is a valid target (not self-recursion, decryptor, or dispatcher)
    /// - Is smaller than the inlining threshold
    /// - Is pure or read-only (no global side effects)
    /// - Does not contain recursive calls
    ///
    /// # Arguments
    ///
    /// * `callee_token` - Token of the method being considered for inlining.
    ///
    /// # Returns
    ///
    /// `true` if the method should be inlined.
    fn should_inline(&self, callee_token: Token) -> bool {
        if !self.is_valid_target(callee_token) {
            return false;
        }

        // Check if we have the callee's SSA and evaluate criteria
        self.analysis_ctx
            .with_ssa(callee_token, |callee_ssa| {
                // Check size threshold
                let instr_count = callee_ssa.instruction_count();
                if instr_count > self.pass.inline_threshold {
                    return false;
                }

                // Check purity - only inline pure or read-only methods
                if !callee_ssa.purity().can_inline() {
                    return false;
                }

                // Check for recursive calls in the callee
                if self.has_recursive_call(callee_token, callee_ssa) {
                    return false;
                }

                true
            })
            .unwrap_or(false)
    }

    /// Checks if a method has any recursive calls (direct or indirect).
    ///
    /// This checks for both direct self-calls and indirect recursion through
    /// the call graph (e.g., A calls B which calls A).
    ///
    /// # Arguments
    ///
    /// * `method_token` - Token of the method to check for recursion.
    /// * `ssa` - The SSA representation of the method.
    ///
    /// # Returns
    ///
    /// `true` if the method contains any recursive calls.
    fn has_recursive_call(&self, method_token: Token, ssa: &SsaFunction) -> bool {
        for block in ssa.blocks() {
            for instr in block.instructions() {
                if let SsaOp::Call { method, .. } | SsaOp::CallVirt { method, .. } = instr.op() {
                    if method.token() == method_token {
                        return true;
                    }
                    // Check for indirect recursion via call graph
                    let callees = self.analysis_ctx.call_graph.callees(method.token());
                    if callees.contains(&method_token) {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Resolves a token to its MethodDef equivalent.
    ///
    /// This is necessary because:
    /// - SSA forms are stored under MethodDef tokens
    /// - Call instructions may use MemberRef tokens even for internal methods
    /// - We need to match MemberRef -> MethodDef to look up the callee's SSA
    ///
    /// # Arguments
    ///
    /// * `token` - The token to resolve (may be MethodDef, MemberRef, or MethodSpec).
    ///
    /// # Returns
    ///
    /// The resolved MethodDef token, or the original token if resolution fails.
    fn resolve_to_method_def(&self, token: Token) -> Token {
        let table_id = token.table();

        // Already a MethodDef - return as-is
        if table_id == 0x06 {
            return token;
        }

        // MemberRef - try to resolve to MethodDef
        if table_id == 0x0A {
            let refs = self.assembly.refs_members();
            if let Some(member_ref_entry) = refs.get(&token) {
                let member_ref = member_ref_entry.value();

                // Only handle method signatures, not fields
                let MemberRefSignature::Method(ref _method_sig) = member_ref.signature else {
                    return token;
                };

                // Check if declared by a TypeDef (internal type)
                if let CilTypeReference::TypeDef(type_ref) = &member_ref.declaredby {
                    if let Some(type_info) = type_ref.upgrade() {
                        if let Some(method) = type_info
                            .query_methods()
                            .name(&member_ref.name)
                            .find_first()
                        {
                            return method.token;
                        }
                    }
                }
            }
        }

        token
    }

    /// Finds all inlinable call sites in the method.
    ///
    /// Scans the caller's SSA for call instructions and evaluates each one
    /// against the inlining criteria.
    ///
    /// # Returns
    ///
    /// A vector of candidates that can be inlined.
    fn find_candidates(&self) -> Vec<InlineCandidate> {
        let mut candidates = Vec::new();

        for (block_idx, instr_idx, instr) in self.caller_ssa.iter_instructions() {
            let raw_callee_token = match instr.op() {
                SsaOp::Call { method, .. } => method.token(),
                SsaOp::CallVirt { method, .. } => {
                    let token = method.token();
                    // Check if this is actually polymorphic
                    if self
                        .analysis_ctx
                        .call_graph
                        .resolver()
                        .is_polymorphic(token)
                    {
                        continue;
                    }
                    token
                }
                _ => continue,
            };

            // Resolve MemberRef tokens to MethodDef tokens for SSA lookup
            let callee_token = self.resolve_to_method_def(raw_callee_token);

            // Try full inlining (for pure methods)
            if self.should_inline(callee_token) {
                candidates.push(InlineCandidate {
                    block_idx,
                    instr_idx,
                    callee_token,
                });
            }
        }

        candidates
    }

    /// Processes a single inlining candidate.
    ///
    /// Performs full body inlining and marks successfully inlined methods in
    /// the analysis context.
    ///
    /// # Arguments
    ///
    /// * `candidate` - The inlining candidate to process.
    ///
    /// # Returns
    ///
    /// `true` if the inlining operation was successful.
    fn process_candidate(&mut self, candidate: &InlineCandidate) -> bool {
        let call_op = match self.caller_ssa.block(candidate.block_idx) {
            Some(block) => match block.instructions().get(candidate.instr_idx) {
                Some(instr) => instr.op().clone(),
                None => return false,
            },
            None => return false,
        };

        // Get the callee SSA
        let Some(callee_ssa) = self
            .analysis_ctx
            .with_ssa(candidate.callee_token, Clone::clone)
        else {
            return false;
        };

        let success = self.inline_call(
            &callee_ssa,
            candidate.block_idx,
            candidate.instr_idx,
            &call_op,
            candidate.callee_token,
        );

        if success {
            self.analysis_ctx.mark_inlined(candidate.callee_token);
        }
        success
    }

    /// Inlines a callee method at a specific call site.
    ///
    /// This method handles different return patterns optimally:
    /// - Constant returns: Replace call with constant assignment
    /// - Pass-through returns: Replace call with copy from argument
    /// - Void returns: Replace call with Nop
    /// - Pure computation: Perform full block inlining
    ///
    /// # Arguments
    ///
    /// * `callee_ssa` - The callee's SSA representation.
    /// * `call_block_idx` - Block index of the call instruction in the caller.
    /// * `call_instr_idx` - Instruction index within the block.
    /// * `call_op` - The call operation being inlined.
    /// * `callee_token` - Token of the callee (for logging).
    ///
    /// # Returns
    ///
    /// `true` if inlining was successful.
    fn inline_call(
        &mut self,
        callee_ssa: &SsaFunction,
        call_block_idx: usize,
        call_instr_idx: usize,
        call_op: &SsaOp,
        callee_token: Token,
    ) -> bool {
        // Extract call information
        let (dest, args) = match call_op {
            SsaOp::Call { dest, args, .. } | SsaOp::CallVirt { dest, args, .. } => {
                (*dest, args.clone())
            }
            _ => return false,
        };

        // For very simple cases, we can do a simpler inline
        match callee_ssa.return_info() {
            ReturnInfo::Constant(value) => {
                if let Some(dest_var) = dest {
                    if let Some(block) = self.caller_ssa.block_mut(call_block_idx) {
                        let instr = &mut block.instructions_mut()[call_instr_idx];
                        instr.set_op(SsaOp::Const {
                            dest: dest_var,
                            value: value.clone(),
                        });
                        self.changes
                            .record(EventKind::MethodInlined)
                            .at(self.caller_token, call_instr_idx)
                            .message(format!("inlined constant {callee_token:?}"));
                        return true;
                    }
                } else {
                    // Void destination but constant return - just remove the call
                    if let Some(block) = self.caller_ssa.block_mut(call_block_idx) {
                        let instr = &mut block.instructions_mut()[call_instr_idx];
                        instr.set_op(SsaOp::Nop);
                        self.changes
                            .record(EventKind::MethodInlined)
                            .at(self.caller_token, call_instr_idx)
                            .message(format!("eliminated pure call {callee_token:?}"));
                        return true;
                    }
                }
            }
            ReturnInfo::PassThrough(param_idx) => {
                if let Some(dest_var) = dest {
                    if let Some(&src_var) = args.get(param_idx) {
                        if let Some(block) = self.caller_ssa.block_mut(call_block_idx) {
                            let instr = &mut block.instructions_mut()[call_instr_idx];
                            instr.set_op(SsaOp::Copy {
                                dest: dest_var,
                                src: src_var,
                            });
                            self.changes
                                .record(EventKind::MethodInlined)
                                .at(self.caller_token, call_instr_idx)
                                .message(format!("inlined passthrough {callee_token:?}"));
                            return true;
                        }
                    }
                }
            }
            ReturnInfo::Void => {
                if let Some(block) = self.caller_ssa.block_mut(call_block_idx) {
                    let instr = &mut block.instructions_mut()[call_instr_idx];
                    instr.set_op(SsaOp::Nop);
                    self.changes
                        .record(EventKind::MethodInlined)
                        .at(self.caller_token, call_instr_idx)
                        .message(format!("eliminated void call {callee_token:?}"));
                    return true;
                }
            }
            ReturnInfo::PureComputation | ReturnInfo::Dynamic | ReturnInfo::Unknown => {
                return self.inline_full(
                    callee_ssa,
                    call_block_idx,
                    call_instr_idx,
                    dest,
                    &args,
                    callee_token,
                );
            }
        }

        false
    }

    /// Performs full SSA inlining by copying blocks from callee into caller.
    ///
    /// This handles the complex case where simple replacement isn't possible.
    /// The algorithm:
    /// 1. Map callee parameters to call arguments
    /// 2. Copy callee instructions with remapped variable IDs
    /// 3. Replace the call with inlined instructions
    /// 4. Handle return value assignment if needed
    ///
    /// Currently only supports single-block callees to keep complexity manageable.
    ///
    /// # Arguments
    ///
    /// * `callee_ssa` - The callee's SSA representation.
    /// * `call_block_idx` - Block index of the call instruction.
    /// * `call_instr_idx` - Instruction index within the block.
    /// * `dest` - Optional destination variable for the call result.
    /// * `args` - Arguments passed to the call.
    /// * `callee_token` - Token of the callee (for logging).
    ///
    /// # Returns
    ///
    /// `true` if full inlining was successful.
    fn inline_full(
        &mut self,
        callee_ssa: &SsaFunction,
        call_block_idx: usize,
        call_instr_idx: usize,
        dest: Option<SsaVarId>,
        args: &[SsaVarId],
        callee_token: Token,
    ) -> bool {
        // Only inline single-block callees for now
        if callee_ssa.blocks().len() != 1 {
            return false;
        }

        let Some(callee_block) = callee_ssa.blocks().first() else {
            return false;
        };

        // Build variable remapping
        let mut var_remap: BTreeMap<SsaVarId, SsaVarId> = BTreeMap::new();

        // Map callee parameters to call arguments
        for (param_idx, &arg_var) in args.iter().enumerate() {
            // Safe: .NET methods have at most 65535 parameters
            #[allow(clippy::cast_possible_truncation)]
            if let Some(param_var) = callee_ssa
                .variables_from_argument(param_idx as u16)
                .find(|v| v.version() == 0)
            {
                var_remap.insert(param_var.id(), arg_var);
            }
        }

        // Collect instructions to inline (excluding return)
        let mut inlined_ops: Vec<SsaOp> = Vec::new();
        let mut return_value: Option<SsaVarId> = None;

        for instr in callee_block.instructions() {
            let op = instr.op();
            if let SsaOp::Return { value } = op {
                return_value = *value;
            } else {
                let remapped_op = Self::remap_op(op, &mut var_remap, callee_ssa, self.caller_ssa);
                inlined_ops.push(remapped_op);
            }
        }

        // Modify the caller
        let Some(block) = self.caller_ssa.block_mut(call_block_idx) else {
            return false;
        };

        // Replace call instruction with first inlined op (or Nop if empty)
        if let Some(first_op) = inlined_ops.first().cloned() {
            block.instructions_mut()[call_instr_idx].set_op(first_op);
        } else {
            block.instructions_mut()[call_instr_idx].set_op(SsaOp::Nop);
        }

        // Insert remaining inlined ops
        let instructions = block.instructions_mut();
        for (i, op) in inlined_ops.into_iter().skip(1).enumerate() {
            instructions.insert(call_instr_idx + 1 + i, SsaInstruction::synthetic(op));
        }

        // Handle return value
        if let (Some(dest_var), Some(ret_var)) = (dest, return_value) {
            let remapped_ret = var_remap.get(&ret_var).copied().unwrap_or(ret_var);

            if dest_var != remapped_ret {
                let Some(block) = self.caller_ssa.block_mut(call_block_idx) else {
                    return false;
                };
                let insert_pos = call_instr_idx + 1;
                block.instructions_mut().insert(
                    insert_pos,
                    SsaInstruction::synthetic(SsaOp::Copy {
                        dest: dest_var,
                        src: remapped_ret,
                    }),
                );
            }
        }

        self.changes
            .record(EventKind::MethodInlined)
            .at(self.caller_token, call_instr_idx)
            .message(format!("fully inlined {callee_token:?}"));
        true
    }

    /// Remaps variables in an SSA operation using the given mapping.
    ///
    /// Creates fresh variables in the caller for any callee variables not
    /// already in the mapping (i.e., variables defined within the callee).
    ///
    /// # Arguments
    ///
    /// * `op` - The SSA operation to remap.
    /// * `var_remap` - Mapping from callee variables to caller variables.
    /// * `callee_ssa` - The callee's SSA (for variable metadata).
    /// * `caller_ssa` - The caller's SSA (for creating new variables).
    ///
    /// # Returns
    ///
    /// A cloned operation with all variables remapped to caller variables.
    fn remap_op(
        op: &SsaOp,
        var_remap: &mut BTreeMap<SsaVarId, SsaVarId>,
        callee_ssa: &SsaFunction,
        caller_ssa: &mut SsaFunction,
    ) -> SsaOp {
        let mut cloned = op.clone();

        // Remap destination
        if let Some(dest) = cloned.dest() {
            let new_dest = Self::get_or_create_var(dest, var_remap, callee_ssa, caller_ssa);
            cloned.set_dest(new_dest);
        }

        // Remap uses
        for used in op.uses() {
            let new_var = var_remap.get(&used).copied().unwrap_or(used);
            cloned.replace_uses(used, new_var);
        }

        cloned
    }

    /// Gets the remapped variable or creates a new one in the caller.
    ///
    /// When creating a new variable, copies the metadata from the callee's
    /// variable to ensure proper type information. The new variable is
    /// registered as a stack temporary in the caller.
    ///
    /// # Arguments
    ///
    /// * `var` - The callee variable to look up or create.
    /// * `var_remap` - Mapping from callee variables to caller variables.
    /// * `callee_ssa` - The callee's SSA (for variable metadata).
    /// * `caller_ssa` - The caller's SSA (for creating new variables).
    ///
    /// # Returns
    ///
    /// The remapped variable ID in the caller's SSA.
    fn get_or_create_var(
        var: SsaVarId,
        var_remap: &mut BTreeMap<SsaVarId, SsaVarId>,
        callee_ssa: &SsaFunction,
        caller_ssa: &mut SsaFunction,
    ) -> SsaVarId {
        if let Some(&remapped) = var_remap.get(&var) {
            return remapped;
        }

        // Allocate a Phi-origin variable for the inlined callee variable.
        // Inlined callee variables are synthetic — use Phi origin since
        // they don't correspond to any real CIL local in the caller.
        let var_type = callee_ssa
            .variable(var)
            .map(|v| v.var_type().clone())
            .unwrap_or(SsaType::Unknown);
        let new_id = caller_ssa.create_variable(
            VariableOrigin::Phi,
            0,
            DefSite::instruction(0, 0),
            var_type,
        );

        var_remap.insert(var, new_id);
        new_id
    }
}

/// Pass that inlines small, pure methods at their call sites.
///
/// This pass operates on a per-method basis but consults the global context
/// to access callee method SSA forms. It identifies call sites where the
/// callee is small and pure, then replaces the call with the inlined body.
#[derive(Debug)]
pub struct InliningPass {
    /// Maximum instruction count for inlining candidates.
    inline_threshold: usize,
}

impl InliningPass {
    /// Creates a new inlining pass.
    ///
    /// # Arguments
    ///
    /// * `threshold` - Maximum instruction count for methods to be inlined.
    #[must_use]
    pub fn new(threshold: usize) -> Self {
        Self {
            inline_threshold: threshold,
        }
    }
}

impl SsaPass for InliningPass {
    fn name(&self) -> &'static str {
        "InliningPass"
    }

    fn description(&self) -> &'static str {
        "Inlines small, pure methods at their call sites"
    }

    fn reads_peer_ssa(&self) -> bool {
        true
    }

    fn provides(&self) -> &[PassCapability] {
        &[PassCapability::InlinedMethods]
    }

    fn requires(&self) -> &[PassCapability] {
        &[PassCapability::DevirtualizedCalls]
    }

    fn run_on_method(
        &self,
        ssa: &mut SsaFunction,
        method_token: Token,
        ctx: &CompilerContext,
        assembly: &CilObject,
    ) -> Result<bool> {
        // Create method-specific inlining context
        let mut inline_ctx = InliningContext::new(self, ssa, method_token, ctx, assembly);

        // Find all candidates
        let candidates = inline_ctx.find_candidates();
        if candidates.is_empty() {
            return Ok(false);
        }

        // Process candidates in reverse order to maintain valid indices
        for candidate in candidates.into_iter().rev() {
            inline_ctx.process_candidate(&candidate);
        }

        // Merge changes back to the analysis context
        let changed = inline_ctx.has_changes();
        if changed {
            ctx.events.merge(&inline_ctx.into_changes());
        }
        Ok(changed)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use crate::{
        analysis::{
            CallGraph, ConstValue, MethodRef, SsaFunctionBuilder, SsaOp, SsaType, SsaVarId,
        },
        compiler::{
            passes::inlining::{InliningContext, InliningPass},
            CompilerContext, SsaPass,
        },
        metadata::token::Token,
        test::helpers::test_assembly_arc,
        CilObject,
    };

    fn test_context() -> CompilerContext {
        CompilerContext::new(Arc::new(CallGraph::new()))
    }

    /// Returns a cached test assembly for use in tests.
    fn test_assembly() -> Arc<CilObject> {
        test_assembly_arc()
    }

    #[test]
    fn test_pass_creation() {
        let pass = InliningPass::new(20);
        assert_eq!(pass.name(), "InliningPass");
        assert_eq!(pass.inline_threshold, 20);

        let pass_custom = InliningPass::new(50);
        assert_eq!(pass_custom.inline_threshold, 50);
    }

    #[test]
    fn test_inline_constant_return() {
        // Callee: returns constant 42
        let callee_token = Token::new(0x06000002);
        let (callee_ssa, callee_v0) = {
            let mut v0_out = SsaVarId::from_index(0);
            let ssa = SsaFunctionBuilder::new(0, 0)
                .build_with(|f| {
                    f.block(0, |b| {
                        let v0 = b.const_i32(42);
                        v0_out = v0;
                        b.ret_val(v0);
                    });
                })
                .unwrap();
            (ssa, v0_out)
        };

        // Caller: calls callee
        let caller_token = Token::new(0x06000001);
        let (mut caller_ssa, call_dest) = {
            let mut dest_out = SsaVarId::from_index(1);
            let ssa = SsaFunctionBuilder::new(0, 0)
                .build_with(|f| {
                    f.block(0, |b| {
                        let dest = b.call(MethodRef::new(callee_token), &[], SsaType::I32);
                        dest_out = dest;
                        b.ret_val(dest);
                    });
                })
                .unwrap();
            (ssa, dest_out)
        };

        // Set up context
        let ctx = test_context();
        ctx.set_ssa(callee_token, callee_ssa.clone());

        // Get the call op before creating context (need to borrow caller_ssa)
        let call_op = caller_ssa.block(0).unwrap().instructions()[0].op().clone();

        // Create inlining context and inline
        let pass = InliningPass::new(20);
        let assembly = test_assembly();
        let mut inline_ctx =
            InliningContext::new(&pass, &mut caller_ssa, caller_token, &ctx, &assembly);
        let result = inline_ctx.inline_call(&callee_ssa, 0, 0, &call_op, callee_token);

        assert!(result, "Inlining should succeed");

        // Check that the call was replaced with a constant
        let block = inline_ctx.caller_ssa.block(0).unwrap();
        let first_instr = &block.instructions()[0];
        match first_instr.op() {
            SsaOp::Const { dest, value } => {
                assert_eq!(*dest, call_dest);
                assert_eq!(*value, ConstValue::I32(42));
            }
            other => panic!("Expected Const, got {:?}", other),
        }

        // Verify the callee's const was created correctly
        let _ = callee_v0;
    }

    #[test]
    fn test_inline_void_pure() {
        // Callee: void method that does nothing impure
        let callee_token = Token::new(0x06000002);
        let callee_ssa = SsaFunctionBuilder::new(0, 0)
            .build_with(|f| {
                f.block(0, |b| b.ret());
            })
            .unwrap();

        // Caller: calls callee
        let caller_token = Token::new(0x06000001);
        let mut caller_ssa = SsaFunctionBuilder::new(0, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    b.call_void(MethodRef::new(callee_token), &[]);
                    b.ret();
                });
            })
            .unwrap();

        // Set up context
        let ctx = test_context();
        ctx.set_ssa(callee_token, callee_ssa.clone());

        // Get the call op before creating context
        let call_op = caller_ssa.block(0).unwrap().instructions()[0].op().clone();

        // Create inlining context and inline
        let pass = InliningPass::new(20);
        let assembly = test_assembly();
        let mut inline_ctx =
            InliningContext::new(&pass, &mut caller_ssa, caller_token, &ctx, &assembly);
        let result = inline_ctx.inline_call(&callee_ssa, 0, 0, &call_op, callee_token);

        assert!(result, "Inlining should succeed");

        // Check that the call was replaced with Nop
        let block = inline_ctx.caller_ssa.block(0).unwrap();
        let first_instr = &block.instructions()[0];
        assert!(
            matches!(first_instr.op(), SsaOp::Nop),
            "Expected Nop, got {:?}",
            first_instr.op()
        );
    }

    #[test]
    fn test_no_inline_self_recursion() {
        let pass = InliningPass::new(20);
        let token = Token::new(0x06000001);
        let ctx = test_context();
        let assembly = test_assembly();

        // Create a dummy SSA for the context
        let mut dummy_ssa = SsaFunctionBuilder::new(0, 0)
            .build_with(|f| {
                f.block(0, |b| b.ret());
            })
            .unwrap();

        let inline_ctx = InliningContext::new(&pass, &mut dummy_ssa, token, &ctx, &assembly);

        // Self-recursion check - is_valid_target returns false for self
        assert!(!inline_ctx.is_valid_target(token));
    }

    #[test]
    fn test_no_inline_large_method() {
        let callee_token = Token::new(0x06000002);
        let caller_token = Token::new(0x06000001);

        // Create a callee with many instructions (> threshold)
        let callee_ssa = SsaFunctionBuilder::new(0, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    for _ in 0..30 {
                        let _ = b.const_i32(0);
                    }
                    b.ret();
                });
            })
            .unwrap();

        let ctx = test_context();
        ctx.set_ssa(callee_token, callee_ssa);

        let pass = InliningPass::new(20);
        let assembly = test_assembly();

        // Create a dummy caller SSA
        let mut caller_ssa = SsaFunctionBuilder::new(0, 0)
            .build_with(|f| {
                f.block(0, |b| b.ret());
            })
            .unwrap();

        let inline_ctx =
            InliningContext::new(&pass, &mut caller_ssa, caller_token, &ctx, &assembly);
        assert!(!inline_ctx.should_inline(callee_token));
    }

    #[test]
    fn test_inline_full_computation() {
        // Callee: returns arg0 + 10
        // This is a PureComputation that requires full inlining
        let callee_token = Token::new(0x06000002);
        let callee_ssa = SsaFunctionBuilder::new(1, 0)
            .build_with(|f| {
                let param0 = f.arg(0, SsaType::I32);
                f.block(0, |b| {
                    let v1 = b.const_i32(10);
                    let v2 = b.add(param0, v1);
                    b.ret_val(v2);
                });
            })
            .unwrap();

        // Caller: calls callee with v0=5, stores result in v3
        let caller_token = Token::new(0x06000001);
        let mut caller_ssa = SsaFunctionBuilder::new(0, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let v0 = b.const_i32(5);
                    let v1 = b.call(MethodRef::new(callee_token), &[v0], SsaType::I32);
                    b.ret_val(v1);
                });
            })
            .unwrap();

        // Set up context
        let ctx = test_context();
        ctx.set_ssa(callee_token, callee_ssa.clone());

        // Get the call op before creating context
        let call_op = caller_ssa.block(0).unwrap().instructions()[1].op().clone();

        // Create inlining context and inline
        let pass = InliningPass::new(20);
        let assembly = test_assembly();
        let mut inline_ctx =
            InliningContext::new(&pass, &mut caller_ssa, caller_token, &ctx, &assembly);
        let result = inline_ctx.inline_call(&callee_ssa, 0, 1, &call_op, callee_token);

        assert!(result, "Full inlining should succeed");

        // Verify the caller now has more instructions
        let block = inline_ctx.caller_ssa.block(0).unwrap();
        assert!(
            block.instructions().len() > 3,
            "Expected inlined instructions, got {} instructions",
            block.instructions().len()
        );

        // Check that the second instruction is now the inlined const 10
        let second_instr = &block.instructions()[1];
        match second_instr.op() {
            SsaOp::Const { value, .. } => {
                assert_eq!(*value, ConstValue::I32(10), "Expected inlined constant 10");
            }
            other => panic!("Expected Const for inlined instruction, got {:?}", other),
        }

        // Check that there's an Add instruction
        let has_add = block
            .instructions()
            .iter()
            .any(|i| matches!(i.op(), SsaOp::Add { .. }));
        assert!(has_add, "Expected Add instruction after inlining");
    }
}