jvmrs 0.1.2

A JVM implementation in Rust with Cranelift JIT, AOT compilation, and WebAssembly support
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
#![allow(dead_code)]
//! Thread-Local Allocation Buffers (TLAB) for fast object allocation
//!
//! TLAB allows each thread to allocate from its own buffer without
//! synchronization, reducing contention and improving allocation speed.

use std::cell::RefCell;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

/// TLAB configuration
#[derive(Debug, Clone)]
pub struct TlabConfig {
    /// Size of each TLAB in bytes
    pub tlab_size: usize,

    /// Maximum number of TLABs in the global pool
    pub max_tlabs: usize,

    /// Enable TLAB allocation
    pub enabled: bool,
}

impl Default for TlabConfig {
    fn default() -> Self {
        Self {
            tlab_size: 64 * 1024, // 64KB per TLAB
            max_tlabs: 16,
            enabled: true,
        }
    }
}

/// Thread-local allocation buffer
pub struct Tlab {
    /// Base pointer of the TLAB
    base: *mut u8,

    /// Current allocation pointer
    top: *mut u8,

    /// End pointer (base + size)
    end: *mut u8,

    /// Thread ID that owns this TLAB
    thread_id: u32,

    /// TLAB size
    size: usize,

    /// Number of allocations from this TLAB
    allocation_count: usize,

    /// Bytes allocated from this TLAB
    bytes_allocated: usize,
}

unsafe impl Send for Tlab {}

impl Tlab {
    /// Create a new TLAB with the given size
    pub fn new(size: usize, thread_id: u32) -> Self {
        let layout = std::alloc::Layout::from_size_align(size, 8)
            .expect("Invalid TLAB size or alignment");
        let base = unsafe { std::alloc::alloc(layout) };
        
        if base.is_null() {
            panic!("Failed to allocate TLAB of {} bytes", size);
        }

        Self {
            base,
            top: base,
            end: unsafe { base.add(size) },
            thread_id,
            size,
            allocation_count: 0,
            bytes_allocated: 0,
        }
    }

    /// Allocate an object from the TLAB
    pub fn allocate(&mut self, size: usize, alignment: usize) -> Option<*mut u8> {
        // Align current pointer
        let aligned_top = (self.top as usize + alignment - 1) & !(alignment - 1);
        let aligned_top = aligned_top as *mut u8;

        // Check if there's enough space
        if unsafe { aligned_top.add(size) } > self.end {
            return None; // TLAB is full
        }

        // Allocate
        let ptr = aligned_top;
        self.top = unsafe { aligned_top.add(size) };
        self.allocation_count += 1;
        self.bytes_allocated += size;

        Some(ptr)
    }

    /// Get remaining space in the TLAB
    pub fn remaining(&self) -> usize {
        self.end as usize - self.top as usize
    }

    /// Get the thread ID that owns this TLAB
    pub fn thread_id(&self) -> u32 {
        self.thread_id
    }

    /// Get allocation statistics
    pub fn stats(&self) -> TlabStats {
        TlabStats {
            allocation_count: self.allocation_count,
            bytes_allocated: self.bytes_allocated,
            remaining: self.remaining(),
            utilization: if self.size > 0 {
                (self.bytes_allocated as f64 / self.size as f64) * 100.0
            } else {
                0.0
            },
        }
    }

    /// Reset the TLAB for reuse
    pub fn reset(&mut self) {
        self.top = self.base;
        self.allocation_count = 0;
        self.bytes_allocated = 0;
    }
}

impl Drop for Tlab {
    fn drop(&mut self) {
        if !self.base.is_null() {
            unsafe {
                if let Ok(layout) = std::alloc::Layout::from_size_align(self.size, 8) {
                    std::alloc::dealloc(self.base, layout);
                }
                // If layout fails, we can't deallocate - this is a critical error
                // but we can't panic in drop, so we log and continue
                log::error!("Failed to create layout for TLAB deallocation");
            }
        }
    }
}

/// TLAB statistics
#[derive(Debug, Clone, Copy)]
pub struct TlabStats {
    pub allocation_count: usize,
    pub bytes_allocated: usize,
    pub remaining: usize,
    pub utilization: f64,
}

/// TLAB manager for the heap
pub struct TlabManager {
    /// Configuration
    config: TlabConfig,

    /// Global TLAB pool (for reuse)
    pool: RefCell<Vec<Option<Tlab>>>,

    /// Thread-local TLABs
    thread_tlabs: RefCell<Vec<Option<Tlab>>>,

    /// Statistics
    total_allocations: Arc<AtomicUsize>,
    tlab_hits: Arc<AtomicUsize>,
    tlab_misses: Arc<AtomicUsize>,
}

impl TlabManager {
    /// Create a new TLAB manager
    pub fn new(config: TlabConfig) -> Self {
        let pool = (0..config.max_tlabs).map(|_| None).collect();

        Self {
            config,
            pool: RefCell::new(pool),
            thread_tlabs: RefCell::new(Vec::new()),
            total_allocations: Arc::new(AtomicUsize::new(0)),
            tlab_hits: Arc::new(AtomicUsize::new(0)),
            tlab_misses: Arc::new(AtomicUsize::new(0)),
        }
    }

    /// Get or create a TLAB for the current thread
    pub fn get_tlab(&self, thread_id: u32) -> Option<*mut Tlab> {
        if !self.config.enabled {
            return None;
        }

        // Check if thread already has a TLAB
        {
            let mut tlabs = self.thread_tlabs.borrow_mut();
            if let Some(idx) = tlabs.iter().position(|t| {
                t.as_ref()
                    .map(|t| t.thread_id() == thread_id)
                    .unwrap_or(false)
            }) {
                return tlabs[idx].as_mut().map(|t| t as *mut Tlab);
            }
        }

        // Try to get a TLAB from the pool
        let mut pool = self.pool.borrow_mut();
        for tlab in pool.iter_mut() {
            if tlab.is_some() {
                let tlab_obj = tlab.take().unwrap();

                // Add to thread-local TLABs
                let mut tlabs = self.thread_tlabs.borrow_mut();
                tlabs.push(Some(tlab_obj));

                return tlabs
                    .last_mut()
                    .and_then(|t| t.as_mut())
                    .map(|t| t as *mut Tlab);
            }
        }

        // Create a new TLAB
        let tlab_obj = Tlab::new(self.config.tlab_size, thread_id);
        let mut tlabs = self.thread_tlabs.borrow_mut();
        tlabs.push(Some(tlab_obj));

        tlabs
            .last_mut()
            .and_then(|t| t.as_mut())
            .map(|t| t as *mut Tlab)
    }

    /// Allocate an object using TLAB
    pub fn allocate(&self, size: usize, alignment: usize, thread_id: u32) -> Option<*mut u8> {
        self.total_allocations.fetch_add(1, Ordering::Relaxed);

        if let Some(tlab_ptr) = self.get_tlab(thread_id) {
            unsafe {
                let tlab = &mut *tlab_ptr;
                if let Some(ptr) = tlab.allocate(size, alignment) {
                    self.tlab_hits.fetch_add(1, Ordering::Relaxed);
                    return Some(ptr);
                }

                // TLAB is full, return it to the pool
                self.tlab_misses.fetch_add(1, Ordering::Relaxed);

                // Find slot in pool
                let mut pool = self.pool.borrow_mut();
                for slot in pool.iter_mut() {
                    if slot.is_none() {
                        let mut new_tlab = Tlab::new(self.config.tlab_size, thread_id);
                        std::mem::swap(tlab, &mut new_tlab);
                        *slot = Some(new_tlab);
                        break;
                    }
                }
            }
        }

        // Fall back to heap allocation
        None
    }

    /// Get TLAB statistics
    pub fn stats(&self) -> TlabManagerStats {
        let total = self.total_allocations.load(Ordering::Relaxed);
        let hits = self.tlab_hits.load(Ordering::Relaxed);
        let misses = self.tlab_misses.load(Ordering::Relaxed);

        TlabManagerStats {
            total_allocations: total,
            tlab_hits: hits,
            tlab_misses: misses,
            hit_rate: if total > 0 {
                (hits as f64 / total as f64) * 100.0
            } else {
                0.0
            },
            active_tlabs: self.thread_tlabs.borrow().len(),
        }
    }

    /// Reset all TLABs (e.g., after GC)
    pub fn reset_all(&self) {
        let mut tlabs = self.thread_tlabs.borrow_mut();
        for tlab in tlabs.iter_mut() {
            if let Some(t) = tlab {
                t.reset();
            }
        }
    }

    /// Clear all TLABs (e.g., for thread shutdown)
    pub fn clear_all(&self) {
        self.thread_tlabs.borrow_mut().clear();
    }
}

/// TLAB manager statistics
#[derive(Debug, Clone, Copy)]
pub struct TlabManagerStats {
    pub total_allocations: usize,
    pub tlab_hits: usize,
    pub tlab_misses: usize,
    pub hit_rate: f64,
    pub active_tlabs: usize,
}

impl Default for TlabManager {
    fn default() -> Self {
        Self::new(TlabConfig::default())
    }
}

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

    #[test]
    fn test_tlab_allocation() {
        let mut tlab = Tlab::new(1024, 1);

        // Allocate small object
        let ptr1 = tlab.allocate(16, 8);
        assert!(ptr1.is_some());
        assert_eq!(tlab.stats().allocation_count, 1);

        // Allocate another object
        let ptr2 = tlab.allocate(32, 8);
        assert!(ptr2.is_some());
        assert_eq!(tlab.stats().allocation_count, 2);

        // Pointers should be different
        assert_ne!(ptr1.unwrap(), ptr2.unwrap());
    }

    #[test]
    fn test_tlab_full() {
        let mut tlab = Tlab::new(100, 1);

        // Allocate 90 bytes
        let ptr1 = tlab.allocate(90, 8);
        assert!(ptr1.is_some());

        // Try to allocate 20 bytes (should fail)
        let ptr2 = tlab.allocate(20, 8);
        assert!(ptr2.is_none());
    }

    #[test]
    fn test_tlab_reset() {
        let mut tlab = Tlab::new(1024, 1);

        // Allocate some objects
        tlab.allocate(100, 8);
        tlab.allocate(200, 8);

        assert_eq!(tlab.stats().allocation_count, 2);

        // Reset TLAB
        tlab.reset();

        assert_eq!(tlab.stats().allocation_count, 0);
        assert_eq!(tlab.stats().bytes_allocated, 0);
    }

    #[test]
    fn test_tlab_manager() {
        let manager = TlabManager::new(TlabConfig {
            tlab_size: 1024,
            max_tlabs: 2,
            enabled: true,
        });

        // Allocate using TLAB
        let ptr = manager.allocate(100, 8, 1);
        assert!(ptr.is_some());

        let stats = manager.stats();
        assert_eq!(stats.total_allocations, 1);
        assert_eq!(stats.tlab_hits, 1);
    }

    #[test]
    fn test_tlab_stats() {
        let mut tlab = Tlab::new(1024, 1);

        tlab.allocate(100, 8);
        tlab.allocate(200, 8);

        let stats = tlab.stats();
        assert_eq!(stats.allocation_count, 2);
        assert_eq!(stats.bytes_allocated, 300);
        assert!(stats.utilization > 0.0);
    }

    #[test]
    fn test_tlab_alignment() {
        let mut tlab = Tlab::new(1024, 1);

        // Allocate with different alignments
        let ptr1 = tlab.allocate(16, 8);
        let ptr2 = tlab.allocate(32, 16);
        let ptr3 = tlab.allocate(64, 32);

        assert!(ptr1.is_some());
        assert!(ptr2.is_some());
        assert!(ptr3.is_some());

        // Check alignments
        assert_eq!(ptr1.unwrap() as usize % 8, 0);
        assert_eq!(ptr2.unwrap() as usize % 16, 0);
        assert_eq!(ptr3.unwrap() as usize % 32, 0);
    }
}