torsh-jit 0.1.3

JIT compilation and kernel fusion for ToRSh deep learning framework
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
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
//! Profiler integration for JIT compilation
//!
//! This module provides comprehensive profiling capabilities for JIT-compiled code,
//! including performance counters, sampling profilers, and external profiler integration.

use crate::{JitError, JitResult};
use indexmap::IndexMap;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Profiler manager for JIT compilation
#[derive(Debug)]
pub struct ProfilerManager {
    /// Active profiling sessions
    sessions: Arc<Mutex<IndexMap<String, ProfilingSession>>>,

    /// Performance counters
    counters: Arc<Mutex<PerformanceCounters>>,

    /// Profiler configuration
    config: ProfilerConfig,

    /// External profiler integrations
    external_profilers: Vec<Box<dyn ExternalProfiler>>,

    /// Sampling profiler
    sampling_profiler: Option<SamplingProfiler>,

    /// Global profiling statistics
    stats: Arc<Mutex<ProfilerStats>>,

    /// Session counter for generating unique IDs
    session_counter: Arc<Mutex<u64>>,
}

/// Profiling session for tracking execution
#[derive(Debug, Clone)]
pub struct ProfilingSession {
    /// Session ID
    pub id: String,

    /// Session name
    pub name: String,

    /// Start time
    pub start_time: Instant,

    /// Duration (if completed)
    pub duration: Option<Duration>,

    /// Performance events collected
    pub events: Vec<PerformanceEvent>,

    /// Function call stacks
    pub call_stacks: Vec<CallStack>,

    /// Memory allocation tracking
    pub memory_events: Vec<MemoryEvent>,

    /// Hardware performance counters
    pub hw_counters: HardwareCounters,

    /// Session metadata
    pub metadata: HashMap<String, String>,

    /// Session status
    pub status: SessionStatus,
}

/// Status of a profiling session
#[derive(Debug, Clone, PartialEq)]
pub enum SessionStatus {
    Active,
    Completed,
    Failed(String),
    Cancelled,
}

/// Performance event types
#[derive(Debug, Clone)]
pub enum PerformanceEvent {
    /// Function entry
    FunctionEntry {
        function_name: String,
        timestamp: Instant,
        thread_id: u64,
        address: u64,
    },

    /// Function exit
    FunctionExit {
        function_name: String,
        timestamp: Instant,
        thread_id: u64,
        duration: Duration,
    },

    /// Kernel launch (for GPU code)
    KernelLaunch {
        kernel_name: String,
        timestamp: Instant,
        grid_size: (u32, u32, u32),
        block_size: (u32, u32, u32),
    },

    /// Kernel completion
    KernelComplete {
        kernel_name: String,
        timestamp: Instant,
        duration: Duration,
        occupancy: f32,
    },

    /// Memory allocation
    MemoryAlloc {
        size: usize,
        address: u64,
        timestamp: Instant,
        alignment: usize,
    },

    /// Memory deallocation
    MemoryFree { address: u64, timestamp: Instant },

    /// Cache miss
    CacheMiss {
        level: u8,
        address: u64,
        timestamp: Instant,
    },

    /// Branch misprediction
    BranchMisprediction {
        address: u64,
        timestamp: Instant,
        target_address: u64,
    },

    /// Custom user event
    Custom {
        name: String,
        timestamp: Instant,
        data: HashMap<String, String>,
    },
}

/// Call stack representation
#[derive(Debug, Clone)]
pub struct CallStack {
    /// Timestamp when stack was captured
    pub timestamp: Instant,

    /// Thread ID
    pub thread_id: u64,

    /// Stack frames (bottom to top)
    pub frames: Vec<StackFrame>,

    /// Total depth
    pub depth: usize,
}

/// Stack frame information
#[derive(Debug, Clone)]
pub struct StackFrame {
    /// Function name
    pub function_name: String,

    /// Address
    pub address: u64,

    /// Source location (if available)
    pub source_location: Option<SourceLocation>,

    /// Inlined function information
    pub inlined: bool,

    /// Module name
    pub module_name: String,
}

/// Source location for profiling
#[derive(Debug, Clone)]
pub struct SourceLocation {
    pub file: String,
    pub line: u32,
    pub column: u32,
}

/// Memory event tracking
#[derive(Debug, Clone)]
pub enum MemoryEvent {
    /// Allocation
    Alloc {
        size: usize,
        address: u64,
        timestamp: Instant,
        stack_trace: Vec<StackFrame>,
    },

    /// Deallocation
    Free {
        address: u64,
        timestamp: Instant,
        stack_trace: Vec<StackFrame>,
    },

    /// Memory access
    Access {
        address: u64,
        size: usize,
        is_write: bool,
        timestamp: Instant,
    },

    /// Page fault
    PageFault {
        address: u64,
        timestamp: Instant,
        fault_type: PageFaultType,
    },
}

/// Page fault types
#[derive(Debug, Clone)]
pub enum PageFaultType {
    Major,
    Minor,
    Protection,
}

/// Hardware performance counters
#[derive(Debug, Clone, Default)]
pub struct HardwareCounters {
    /// CPU cycles
    pub cycles: u64,

    /// Instructions executed
    pub instructions: u64,

    /// Cache misses (L1, L2, L3)
    pub cache_misses: [u64; 3],

    /// Cache references
    pub cache_references: u64,

    /// Branch mispredictions
    pub branch_mispredictions: u64,

    /// Branch instructions
    pub branches: u64,

    /// Page faults
    pub page_faults: u64,

    /// Context switches
    pub context_switches: u64,

    /// CPU migrations
    pub cpu_migrations: u64,

    /// Custom counters
    pub custom_counters: HashMap<String, u64>,
}

/// Global performance counters
#[derive(Debug, Clone, Default)]
pub struct PerformanceCounters {
    /// Total compilation time
    pub total_compile_time: Duration,

    /// Total execution time
    pub total_execution_time: Duration,

    /// Number of compilations
    pub compilation_count: u64,

    /// Number of executions
    pub execution_count: u64,

    /// Memory usage statistics
    pub memory_stats: MemoryStats,

    /// Function call counts
    pub function_calls: HashMap<String, u64>,

    /// Kernel launch counts
    pub kernel_launches: HashMap<String, u64>,

    /// Error counts
    pub error_counts: HashMap<String, u64>,
}

/// Memory usage statistics
#[derive(Debug, Clone, Default)]
pub struct MemoryStats {
    /// Current memory usage
    pub current_usage: usize,

    /// Peak memory usage
    pub peak_usage: usize,

    /// Total allocations
    pub total_allocations: u64,

    /// Total deallocations
    pub total_deallocations: u64,

    /// Total bytes allocated
    pub total_bytes_allocated: u64,

    /// Total bytes freed
    pub total_bytes_freed: u64,

    /// Average allocation size
    pub avg_allocation_size: f64,

    /// Allocation histogram
    pub allocation_histogram: HashMap<usize, u64>,
}

/// Profiler configuration
#[derive(Debug, Clone)]
pub struct ProfilerConfig {
    /// Enable profiling
    pub enabled: bool,

    /// Sampling frequency in Hz
    pub sampling_frequency: u32,

    /// Enable call stack collection
    pub collect_call_stacks: bool,

    /// Enable memory tracking
    pub track_memory: bool,

    /// Enable hardware counter collection
    pub collect_hardware_counters: bool,

    /// Maximum number of events per session
    pub max_events_per_session: usize,

    /// Enable external profiler integration
    pub enable_external_profilers: bool,

    /// Output format for profiling data
    pub output_format: ProfilerOutputFormat,

    /// Output directory
    pub output_directory: String,
}

/// Profiler output formats
#[derive(Debug, Clone)]
pub enum ProfilerOutputFormat {
    /// Chrome tracing format
    ChromeTracing,

    /// Linux perf format
    PerfData,

    /// Intel VTune format
    VTune,

    /// Custom JSON format
    Json,

    /// Binary format
    Binary,
}

/// Sampling profiler for continuous monitoring
#[derive(Debug)]
pub struct SamplingProfiler {
    /// Sampling thread handle
    thread_handle: Option<std::thread::JoinHandle<()>>,

    /// Sampling configuration
    config: SamplingConfig,

    /// Collected samples
    samples: Arc<Mutex<Vec<Sample>>>,

    /// Running flag
    running: Arc<Mutex<bool>>,
}

/// Sampling configuration
#[derive(Debug, Clone)]
pub struct SamplingConfig {
    /// Sampling interval
    pub interval: Duration,

    /// Enable stack trace collection
    pub collect_stacks: bool,

    /// Maximum stack depth
    pub max_stack_depth: usize,

    /// Target threads (empty = all threads)
    pub target_threads: Vec<u64>,
}

/// Profiling sample
#[derive(Debug, Clone)]
pub struct Sample {
    /// Timestamp
    pub timestamp: Instant,

    /// Thread ID
    pub thread_id: u64,

    /// CPU ID
    pub cpu_id: u32,

    /// Program counter
    pub pc: u64,

    /// Stack trace
    pub stack_trace: Option<Vec<StackFrame>>,

    /// CPU utilization
    pub cpu_utilization: f32,

    /// Memory usage
    pub memory_usage: usize,
}

/// External profiler trait
pub trait ExternalProfiler: Send + Sync + std::fmt::Debug {
    /// Start profiling
    fn start(&mut self) -> JitResult<()>;

    /// Stop profiling
    fn stop(&mut self) -> JitResult<()>;

    /// Add a function to profile
    fn add_function(&mut self, name: &str, address: u64, size: usize) -> JitResult<()>;

    /// Remove a function from profiling
    fn remove_function(&mut self, address: u64) -> JitResult<()>;

    /// Export profiling data
    fn export_data(&self, output_path: &str) -> JitResult<()>;

    /// Get profiler name
    fn name(&self) -> &str;
}

/// Linux perf profiler integration
#[derive(Debug)]
pub struct PerfProfiler {
    /// Perf session active
    active: bool,

    /// Function mappings
    function_map: HashMap<u64, String>,

    /// JIT dump file
    jit_dump_file: Option<std::fs::File>,

    /// Map file path
    map_file: Option<std::path::PathBuf>,
}

/// Intel VTune profiler integration
#[derive(Debug)]
pub struct VTuneProfiler {
    /// VTune session active
    active: bool,

    /// Function mappings
    function_map: HashMap<u64, String>,
}

/// Profiler statistics
#[derive(Debug, Clone, Default)]
pub struct ProfilerStats {
    /// Total sessions created
    pub total_sessions: u64,

    /// Active sessions
    pub active_sessions: u64,

    /// Total events collected
    pub total_events: u64,

    /// Total samples collected
    pub total_samples: u64,

    /// Profiling overhead percentage
    pub overhead_percentage: f32,

    /// Data export count
    pub export_count: u64,
}

impl Default for ProfilerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            sampling_frequency: 1000, // 1 KHz
            collect_call_stacks: true,
            track_memory: true,
            collect_hardware_counters: false, // Requires privileged access
            max_events_per_session: 1_000_000,
            enable_external_profilers: false,
            output_format: ProfilerOutputFormat::Json,
            output_directory: std::env::temp_dir()
                .join("torsh_profiling")
                .display()
                .to_string(),
        }
    }
}

impl ProfilerManager {
    /// Create a new profiler manager
    pub fn new(config: ProfilerConfig) -> Self {
        Self {
            sessions: Arc::new(Mutex::new(IndexMap::new())),
            counters: Arc::new(Mutex::new(PerformanceCounters::default())),
            config,
            external_profilers: Vec::new(),
            sampling_profiler: None,
            stats: Arc::new(Mutex::new(ProfilerStats::default())),
            session_counter: Arc::new(Mutex::new(0)),
        }
    }

    /// Create a new profiler manager with default configuration
    pub fn with_defaults() -> Self {
        Self::new(ProfilerConfig::default())
    }

    /// Start a new profiling session
    pub fn start_session(&mut self, name: &str) -> JitResult<String> {
        if !self.config.enabled {
            return Err(JitError::RuntimeError("Profiling disabled".to_string()));
        }

        let session_id = {
            let mut counter = self
                .session_counter
                .lock()
                .expect("lock should not be poisoned");
            *counter += 1;
            format!("session_{}", *counter)
        };
        let session = ProfilingSession {
            id: session_id.clone(),
            name: name.to_string(),
            start_time: Instant::now(),
            duration: None,
            events: Vec::new(),
            call_stacks: Vec::new(),
            memory_events: Vec::new(),
            hw_counters: HardwareCounters::default(),
            metadata: HashMap::new(),
            status: SessionStatus::Active,
        };

        {
            let mut sessions = self.sessions.lock().expect("lock should not be poisoned");
            sessions.insert(session_id.clone(), session);
        }

        {
            let mut stats = self.stats.lock().expect("lock should not be poisoned");
            stats.total_sessions += 1;
            stats.active_sessions += 1;
        }

        // Start external profilers if enabled
        if self.config.enable_external_profilers {
            for profiler in &mut self.external_profilers {
                profiler.start()?;
            }
        }

        Ok(session_id)
    }

    /// Stop a profiling session
    pub fn stop_session(&mut self, session_id: &str) -> JitResult<()> {
        let mut sessions = self.sessions.lock().expect("lock should not be poisoned");

        if let Some(session) = sessions.get_mut(session_id) {
            session.duration = Some(session.start_time.elapsed());
            session.status = SessionStatus::Completed;

            let mut stats = self.stats.lock().expect("lock should not be poisoned");
            stats.active_sessions = stats.active_sessions.saturating_sub(1);
        } else {
            return Err(JitError::RuntimeError(format!(
                "Session {} not found",
                session_id
            )));
        }

        // Stop external profilers if no active sessions
        let active_count = {
            let stats = self.stats.lock().expect("lock should not be poisoned");
            stats.active_sessions
        };

        if active_count == 0 && self.config.enable_external_profilers {
            for profiler in &mut self.external_profilers {
                profiler.stop()?;
            }
        }

        Ok(())
    }

    /// Record a performance event
    pub fn record_event(&mut self, session_id: &str, event: PerformanceEvent) -> JitResult<()> {
        let mut sessions = self.sessions.lock().expect("lock should not be poisoned");

        if let Some(session) = sessions.get_mut(session_id) {
            if session.events.len() < self.config.max_events_per_session {
                session.events.push(event);

                let mut stats = self.stats.lock().expect("lock should not be poisoned");
                stats.total_events += 1;
            }
        }

        Ok(())
    }

    /// Record a call stack
    pub fn record_call_stack(&mut self, session_id: &str, call_stack: CallStack) -> JitResult<()> {
        if !self.config.collect_call_stacks {
            return Ok(());
        }

        let mut sessions = self.sessions.lock().expect("lock should not be poisoned");

        if let Some(session) = sessions.get_mut(session_id) {
            session.call_stacks.push(call_stack);
        }

        Ok(())
    }

    /// Start sampling profiler
    pub fn start_sampling(&mut self) -> JitResult<()> {
        if self.sampling_profiler.is_some() {
            return Err(JitError::RuntimeError(
                "Sampling profiler already running".to_string(),
            ));
        }

        let config = SamplingConfig {
            interval: Duration::from_nanos(1_000_000_000 / self.config.sampling_frequency as u64),
            collect_stacks: self.config.collect_call_stacks,
            max_stack_depth: 64,
            target_threads: Vec::new(),
        };

        let mut sampling_profiler = SamplingProfiler::new(config)?;
        sampling_profiler.start()?;

        self.sampling_profiler = Some(sampling_profiler);
        Ok(())
    }

    /// Stop sampling profiler
    pub fn stop_sampling(&mut self) -> JitResult<()> {
        if let Some(mut profiler) = self.sampling_profiler.take() {
            profiler.stop()?;
        }
        Ok(())
    }

    /// Add external profiler
    pub fn add_external_profiler(&mut self, profiler: Box<dyn ExternalProfiler>) {
        self.external_profilers.push(profiler);
    }

    /// Export profiling data
    pub fn export_session_data(&self, session_id: &str, output_path: &str) -> JitResult<()> {
        let sessions = self.sessions.lock().expect("lock should not be poisoned");

        if let Some(session) = sessions.get(session_id) {
            match self.config.output_format {
                ProfilerOutputFormat::Json => self.export_json(session, output_path)?,
                ProfilerOutputFormat::ChromeTracing => {
                    self.export_chrome_tracing(session, output_path)?
                }
                _ => {
                    return Err(JitError::RuntimeError(
                        "Unsupported export format".to_string(),
                    ))
                }
            }

            let mut stats = self.stats.lock().expect("lock should not be poisoned");
            stats.export_count += 1;
        }

        Ok(())
    }

    /// Export session data as JSON
    fn export_json(&self, session: &ProfilingSession, output_path: &str) -> JitResult<()> {
        use serde_json::json;

        // Build comprehensive JSON representation
        let events_json: Vec<_> = session
            .events
            .iter()
            .map(|event| {
                json!({
                    "event": format!("{:?}", event)
                })
            })
            .collect();

        let session_json = json!({
            "name": session.name,
            "id": session.id,
            "start_time": session.start_time.elapsed().as_micros(),
            "duration": session.duration.map(|d| d.as_micros()),
            "events": events_json,
            "event_count": session.events.len(),
            "call_stack_count": session.call_stacks.len(),
            "memory_event_count": session.memory_events.len()
        });

        std::fs::write(
            output_path,
            serde_json::to_string_pretty(&session_json)
                .map_err(|e| JitError::RuntimeError(format!("JSON serialization failed: {}", e)))?,
        )
        .map_err(|e| JitError::RuntimeError(format!("Failed to write JSON: {}", e)))?;

        Ok(())
    }

    /// Export session data as Chrome tracing format
    fn export_chrome_tracing(
        &self,
        session: &ProfilingSession,
        output_path: &str,
    ) -> JitResult<()> {
        use serde_json::json;

        // Convert events to Chrome tracing format
        // See https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/
        let mut trace_events = Vec::new();

        for event in &session.events {
            match event {
                PerformanceEvent::FunctionEntry {
                    function_name,
                    timestamp,
                    thread_id,
                    ..
                } => {
                    trace_events.push(json!({
                        "name": function_name,
                        "cat": "function",
                        "ph": "B",  // Begin
                        "ts": timestamp.elapsed().as_micros() as u64,
                        "pid": 1,
                        "tid": thread_id
                    }));
                }
                PerformanceEvent::FunctionExit {
                    function_name,
                    timestamp,
                    thread_id,
                    duration,
                } => {
                    trace_events.push(json!({
                        "name": function_name,
                        "cat": "function",
                        "ph": "E",  // End
                        "ts": timestamp.elapsed().as_micros() as u64,
                        "pid": 1,
                        "tid": thread_id,
                        "args": { "duration_us": duration.as_micros() }
                    }));
                }
                PerformanceEvent::MemoryAlloc {
                    size,
                    timestamp,
                    address,
                    ..
                } => {
                    trace_events.push(json!({
                        "name": "Memory Allocation",
                        "cat": "memory",
                        "ph": "i",  // Instant event
                        "ts": timestamp.elapsed().as_micros() as u64,
                        "pid": 1,
                        "tid": 1,
                        "s": "g",   // Global scope
                        "args": { "size": size, "address": format!("0x{:x}", address) }
                    }));
                }
                PerformanceEvent::CacheMiss {
                    level, timestamp, ..
                } => {
                    trace_events.push(json!({
                        "name": format!("L{} Cache Miss", level),
                        "cat": "cache",
                        "ph": "i",
                        "ts": timestamp.elapsed().as_micros() as u64,
                        "pid": 1,
                        "tid": 1,
                        "s": "t",   // Thread scope
                    }));
                }
                _ => {
                    // Generic event
                    trace_events.push(json!({
                        "name": format!("{:?}", event),
                        "cat": "general",
                        "ph": "i",
                        "ts": 0,
                        "pid": 1,
                        "tid": 1
                    }));
                }
            }
        }

        // Add metadata
        let metadata = json!({
            "process_name": { "1": session.name.clone() },
            "thread_name": { "1": "Main Thread" }
        });

        // Build final trace
        let trace = json!({
            "traceEvents": trace_events,
            "displayTimeUnit": "ms",
            "metadata": metadata
        });

        std::fs::write(
            output_path,
            serde_json::to_string_pretty(&trace)
                .map_err(|e| JitError::RuntimeError(format!("JSON serialization failed: {}", e)))?,
        )
        .map_err(|e| JitError::RuntimeError(format!("Failed to write tracing data: {}", e)))?;

        Ok(())
    }

    /// Get session data
    pub fn get_session(&self, session_id: &str) -> Option<ProfilingSession> {
        let sessions = self.sessions.lock().expect("lock should not be poisoned");
        sessions.get(session_id).cloned()
    }

    /// Get performance counters
    pub fn get_counters(&self) -> PerformanceCounters {
        let counters = self.counters.lock().expect("lock should not be poisoned");
        counters.clone()
    }

    /// Get profiler statistics
    pub fn get_stats(&self) -> ProfilerStats {
        let stats = self.stats.lock().expect("lock should not be poisoned");
        stats.clone()
    }

    /// Update performance counters
    pub fn update_counters<F>(&self, update_fn: F)
    where
        F: FnOnce(&mut PerformanceCounters),
    {
        let mut counters = self.counters.lock().expect("lock should not be poisoned");
        update_fn(&mut *counters);
    }
}

impl SamplingProfiler {
    /// Create a new sampling profiler
    pub fn new(config: SamplingConfig) -> JitResult<Self> {
        Ok(Self {
            thread_handle: None,
            config,
            samples: Arc::new(Mutex::new(Vec::new())),
            running: Arc::new(Mutex::new(false)),
        })
    }

    /// Start sampling
    pub fn start(&mut self) -> JitResult<()> {
        let running = self.running.clone();
        let samples = self.samples.clone();
        let config = self.config.clone();

        *running.lock().expect("lock should not be poisoned") = true;

        let thread_handle = std::thread::spawn(move || {
            let mut last_sample_time = Instant::now();

            while *running.lock().expect("lock should not be poisoned") {
                let now = Instant::now();

                // Collect sample with actual system information
                let sample = Sample {
                    timestamp: now,
                    thread_id: Self::get_thread_id(),
                    cpu_id: Self::get_cpu_id(),
                    pc: 0, // Program counter requires platform-specific code
                    stack_trace: Self::collect_stack_trace(),
                    cpu_utilization: Self::calculate_cpu_utilization(&last_sample_time, &now),
                    memory_usage: Self::get_memory_usage(),
                };

                {
                    let mut samples_guard = samples.lock().expect("lock should not be poisoned");
                    samples_guard.push(sample);
                }

                last_sample_time = now;

                std::thread::sleep(config.interval);
            }
        });

        self.thread_handle = Some(thread_handle);
        Ok(())
    }

    /// Stop sampling
    pub fn stop(&mut self) -> JitResult<()> {
        *self.running.lock().expect("lock should not be poisoned") = false;

        if let Some(handle) = self.thread_handle.take() {
            handle.join().map_err(|_| {
                JitError::RuntimeError("Failed to join sampling thread".to_string())
            })?;
        }

        Ok(())
    }

    /// Get collected samples
    pub fn get_samples(&self) -> Vec<Sample> {
        let samples = self.samples.lock().expect("lock should not be poisoned");
        samples.clone()
    }

    /// Get the current thread ID
    fn get_thread_id() -> u64 {
        // Use thread name hash for portability
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        std::thread::current().id().hash(&mut hasher);
        hasher.finish()
    }

    /// Get the current CPU ID
    fn get_cpu_id() -> u32 {
        // Platform-specific CPU ID retrieval
        // For cross-platform compatibility, default to 0
        0
    }

    /// Collect stack trace
    fn collect_stack_trace() -> Option<Vec<StackFrame>> {
        // Use backtrace-rs or similar library in production
        // For now, return a simple placeholder
        Some(vec![StackFrame {
            function_name: "sampling_thread".to_string(),
            address: 0,
            source_location: Some(SourceLocation {
                file: "profiler.rs".to_string(),
                line: 0,
                column: 0,
            }),
            inlined: false,
            module_name: "torsh_jit".to_string(),
        }])
    }

    /// Calculate CPU utilization
    fn calculate_cpu_utilization(_last_time: &Instant, _current_time: &Instant) -> f32 {
        // This would require platform-specific CPU time queries
        // Placeholder implementation
        (num_cpus::get() as f32) * 0.5 // Assume 50% utilization
    }

    /// Get current memory usage
    fn get_memory_usage() -> usize {
        // Platform-specific memory usage
        #[cfg(target_os = "linux")]
        {
            if let Ok(status) = std::fs::read_to_string("/proc/self/status") {
                for line in status.lines() {
                    if line.starts_with("VmRSS:") {
                        if let Some(kb_str) = line.split_whitespace().nth(1) {
                            if let Ok(kb) = kb_str.parse::<usize>() {
                                return kb * 1024; // Convert to bytes
                            }
                        }
                    }
                }
            }
        }

        #[cfg(target_os = "macos")]
        {
            use std::process::Command;
            if let Ok(output) = Command::new("ps")
                .args(["-o", "rss=", "-p", &std::process::id().to_string()])
                .output()
            {
                if let Ok(text) = String::from_utf8(output.stdout) {
                    if let Ok(kb) = text.trim().parse::<usize>() {
                        return kb * 1024; // Convert to bytes
                    }
                }
            }
        }

        0 // Default if not available
    }
}

impl ExternalProfiler for PerfProfiler {
    fn start(&mut self) -> JitResult<()> {
        // Initialize perf profiling
        // On Linux, perf uses /tmp/perf-<pid>.map for JIT symbol maps
        // NOTE: This MUST remain as /tmp/ - it's a Linux perf convention requirement
        #[cfg(target_os = "linux")]
        {
            let pid = std::process::id();
            let map_file = format!("/tmp/perf-{}.map", pid);

            // Create or truncate the perf map file
            std::fs::write(&map_file, "")
                .map_err(|e| JitError::RuntimeError(format!("Failed to create perf map: {}", e)))?;

            self.map_file = Some(map_file.into());
        }

        self.active = true;
        Ok(())
    }

    fn stop(&mut self) -> JitResult<()> {
        // Finalize perf profiling
        self.active = false;
        Ok(())
    }

    fn add_function(&mut self, name: &str, address: u64, size: usize) -> JitResult<()> {
        // Add function to perf symbol map
        self.function_map.insert(address, name.to_string());

        // Write to perf map file format: <start_addr> <size> <symbol_name>
        #[cfg(target_os = "linux")]
        {
            if let Some(ref map_file) = self.map_file {
                use std::io::Write;
                let mut file = std::fs::OpenOptions::new()
                    .append(true)
                    .open(map_file)
                    .map_err(|e| {
                        JitError::RuntimeError(format!("Failed to open perf map: {}", e))
                    })?;

                writeln!(file, "{:x} {:x} {}", address, size, name).map_err(|e| {
                    JitError::RuntimeError(format!("Failed to write to perf map: {}", e))
                })?;
            }
        }

        Ok(())
    }

    fn remove_function(&mut self, address: u64) -> JitResult<()> {
        self.function_map.remove(&address);
        // Note: perf map files are append-only, so we can't remove entries
        Ok(())
    }

    fn export_data(&self, output_path: &str) -> JitResult<()> {
        // Export perf-compatible symbol map
        use std::io::Write;
        let mut file = std::fs::File::create(output_path)
            .map_err(|e| JitError::RuntimeError(format!("Failed to create export file: {}", e)))?;

        // Write function map in perf format
        for (address, name) in &self.function_map {
            writeln!(file, "{:x} 0 {}", address, name)
                .map_err(|e| JitError::RuntimeError(format!("Failed to write perf data: {}", e)))?;
        }

        Ok(())
    }

    fn name(&self) -> &str {
        "PerfProfiler"
    }
}

impl ExternalProfiler for VTuneProfiler {
    fn start(&mut self) -> JitResult<()> {
        // Initialize VTune profiling using Intel JIT API
        // VTune uses a shared library interface for JIT notification
        #[cfg(target_os = "linux")]
        {
            // In a full implementation, this would dynamically load libittnotify
            // and call iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED, ...)
            log::info!("VTune profiler started (stub implementation)");
        }

        #[cfg(target_os = "windows")]
        {
            log::info!("VTune profiler started on Windows (stub implementation)");
        }

        self.active = true;
        Ok(())
    }

    fn stop(&mut self) -> JitResult<()> {
        // Finalize VTune profiling
        self.active = false;
        Ok(())
    }

    fn add_function(&mut self, name: &str, address: u64, size: usize) -> JitResult<()> {
        // Add function to VTune using JIT API
        self.function_map.insert(address, name.to_string());

        if self.active {
            // In a full implementation, this would call:
            // iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED, method_load_info)
            // where method_load_info contains: method_id, method_name,
            // method_load_address, method_size, line_number_table, etc.

            log::debug!(
                "Registered function '{}' at 0x{:x} (size: {}) with VTune",
                name,
                address,
                size
            );
        }

        Ok(())
    }

    fn remove_function(&mut self, address: u64) -> JitResult<()> {
        self.function_map.remove(&address);

        if self.active {
            // In a full implementation, this would call:
            // iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_UNLOAD_START, method_id)
            log::debug!("Unregistered function at 0x{:x} from VTune", address);
        }

        Ok(())
    }

    fn export_data(&self, output_path: &str) -> JitResult<()> {
        // Export VTune-compatible symbol data
        use std::io::Write;
        let mut file = std::fs::File::create(output_path)
            .map_err(|e| JitError::RuntimeError(format!("Failed to create export file: {}", e)))?;

        // Write header
        writeln!(file, "# VTune JIT Symbol Map")
            .map_err(|e| JitError::RuntimeError(format!("Write failed: {}", e)))?;
        writeln!(file, "# Format: <address> <size> <name>")
            .map_err(|e| JitError::RuntimeError(format!("Write failed: {}", e)))?;
        writeln!(file).map_err(|e| JitError::RuntimeError(format!("Write failed: {}", e)))?;

        // Write function map
        for (address, name) in &self.function_map {
            writeln!(file, "{:016x} 0000 {}", address, name).map_err(|e| {
                JitError::RuntimeError(format!("Failed to write VTune data: {}", e))
            })?;
        }

        Ok(())
    }

    fn name(&self) -> &str {
        "VTuneProfiler"
    }
}

impl PerfProfiler {
    /// Create a new perf profiler
    pub fn new() -> Self {
        Self {
            active: false,
            function_map: HashMap::new(),
            jit_dump_file: None,
            map_file: None,
        }
    }
}

impl VTuneProfiler {
    /// Create a new VTune profiler
    pub fn new() -> Self {
        Self {
            active: false,
            function_map: HashMap::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_profiler_manager_creation() {
        let manager = ProfilerManager::with_defaults();
        assert!(manager.config.enabled);
        assert_eq!(manager.config.sampling_frequency, 1000);
    }

    #[test]
    fn test_session_lifecycle() {
        let mut manager = ProfilerManager::with_defaults();

        let session_id = manager.start_session("test_session").unwrap();
        assert!(!session_id.is_empty());

        let session = manager.get_session(&session_id).unwrap();
        assert_eq!(session.name, "test_session");
        assert_eq!(session.status, SessionStatus::Active);

        manager.stop_session(&session_id).unwrap();

        let session = manager.get_session(&session_id).unwrap();
        assert_eq!(session.status, SessionStatus::Completed);
        assert!(session.duration.is_some());
    }

    #[test]
    fn test_performance_event_recording() {
        let mut manager = ProfilerManager::with_defaults();
        let session_id = manager.start_session("test_session").unwrap();

        let event = PerformanceEvent::FunctionEntry {
            function_name: "test_function".to_string(),
            timestamp: Instant::now(),
            thread_id: 1,
            address: 0x1000,
        };

        manager.record_event(&session_id, event).unwrap();

        let session = manager.get_session(&session_id).unwrap();
        assert_eq!(session.events.len(), 1);
    }

    #[test]
    fn test_external_profiler_integration() {
        let mut manager = ProfilerManager::with_defaults();
        let perf_profiler = Box::new(PerfProfiler::new());

        manager.add_external_profiler(perf_profiler);
        assert_eq!(manager.external_profilers.len(), 1);
    }
}