-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.rs
4527 lines (3839 loc) · 158 KB
/
core.rs
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
//! Code versioning, retained live control flow graph mutations, type tracking, etc.
// So we can comment on individual uses of `unsafe` in `unsafe` functions
#![warn(unsafe_op_in_unsafe_fn)]
use crate::asm::*;
use crate::backend::ir::*;
use crate::codegen::*;
use crate::virtualmem::CodePtr;
use crate::cruby::*;
use crate::options::*;
use crate::stats::*;
use crate::utils::*;
#[cfg(feature="disasm")]
use crate::disasm::*;
use core::ffi::c_void;
use std::cell::*;
use std::fmt;
use std::mem;
use std::mem::transmute;
use std::ops::Range;
use std::rc::Rc;
use std::collections::HashSet;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use mem::MaybeUninit;
use std::ptr;
use ptr::NonNull;
use YARVOpnd::*;
use TempMapping::*;
use crate::invariants::*;
// Maximum number of temp value types or registers we keep track of
pub const MAX_CTX_TEMPS: usize = 8;
// Maximum number of local variable types or registers we keep track of
const MAX_CTX_LOCALS: usize = 8;
/// An index into `ISEQ_BODY(iseq)->iseq_encoded`. Points
/// to a YARV instruction or an instruction operand.
pub type IseqIdx = u16;
// Represent the type of a value (local/stack/self) in YJIT
#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum Type {
Unknown = 0,
UnknownImm,
UnknownHeap,
Nil,
True,
False,
Fixnum,
Flonum,
ImmSymbol,
TString, // An object with the T_STRING flag set, possibly an rb_cString
CString, // An object that at one point had its class field equal rb_cString (creating a singleton class changes it)
TArray, // An object with the T_ARRAY flag set, possibly an rb_cArray
CArray, // An object that at one point had its class field equal rb_cArray (creating a singleton class changes it)
THash, // An object with the T_HASH flag set, possibly an rb_cHash
CHash, // An object that at one point had its class field equal rb_cHash (creating a singleton class changes it)
BlockParamProxy, // A special sentinel value indicating the block parameter should be read from
// the current surrounding cfp
// The context currently relies on types taking at most 4 bits (max value 15)
// to encode, so if we add any more, we will need to refactor the context.
}
// Default initialization
impl Default for Type {
fn default() -> Self {
Type::Unknown
}
}
impl Type {
/// This returns an appropriate Type based on a known value
pub fn from(val: VALUE) -> Type {
if val.special_const_p() {
if val.fixnum_p() {
Type::Fixnum
} else if val.nil_p() {
Type::Nil
} else if val == Qtrue {
Type::True
} else if val == Qfalse {
Type::False
} else if val.static_sym_p() {
Type::ImmSymbol
} else if val.flonum_p() {
Type::Flonum
} else {
unreachable!("Illegal value: {:?}", val)
}
} else {
// Core.rs can't reference rb_cString because it's linked by Rust-only tests.
// But CString vs TString is only an optimisation and shouldn't affect correctness.
#[cfg(not(test))]
match val.class_of() {
class if class == unsafe { rb_cArray } => return Type::CArray,
class if class == unsafe { rb_cHash } => return Type::CHash,
class if class == unsafe { rb_cString } => return Type::CString,
_ => {}
}
// We likewise can't reference rb_block_param_proxy, but it's again an optimisation;
// we can just treat it as a normal Object.
#[cfg(not(test))]
if val == unsafe { rb_block_param_proxy } {
return Type::BlockParamProxy;
}
match val.builtin_type() {
RUBY_T_ARRAY => Type::TArray,
RUBY_T_HASH => Type::THash,
RUBY_T_STRING => Type::TString,
_ => Type::UnknownHeap,
}
}
}
/// Check if the type is an immediate
pub fn is_imm(&self) -> bool {
match self {
Type::UnknownImm => true,
Type::Nil => true,
Type::True => true,
Type::False => true,
Type::Fixnum => true,
Type::Flonum => true,
Type::ImmSymbol => true,
_ => false,
}
}
/// Returns true when the type is not specific.
pub fn is_unknown(&self) -> bool {
match self {
Type::Unknown | Type::UnknownImm | Type::UnknownHeap => true,
_ => false,
}
}
/// Returns true when we know the VALUE is a specific handle type,
/// such as a static symbol ([Type::ImmSymbol], i.e. true from RB_STATIC_SYM_P()).
/// Opposite of [Self::is_unknown].
pub fn is_specific(&self) -> bool {
!self.is_unknown()
}
/// Check if the type is a heap object
pub fn is_heap(&self) -> bool {
match self {
Type::UnknownHeap => true,
Type::TArray => true,
Type::CArray => true,
Type::THash => true,
Type::CHash => true,
Type::TString => true,
Type::CString => true,
Type::BlockParamProxy => true,
_ => false,
}
}
/// Check if it's a T_ARRAY object (both TArray and CArray are T_ARRAY)
pub fn is_array(&self) -> bool {
matches!(self, Type::TArray | Type::CArray)
}
/// Check if it's a T_HASH object (both THash and CHash are T_HASH)
pub fn is_hash(&self) -> bool {
matches!(self, Type::THash | Type::CHash)
}
/// Check if it's a T_STRING object (both TString and CString are T_STRING)
pub fn is_string(&self) -> bool {
matches!(self, Type::TString | Type::CString)
}
/// Returns an Option with the T_ value type if it is known, otherwise None
pub fn known_value_type(&self) -> Option<ruby_value_type> {
match self {
Type::Nil => Some(RUBY_T_NIL),
Type::True => Some(RUBY_T_TRUE),
Type::False => Some(RUBY_T_FALSE),
Type::Fixnum => Some(RUBY_T_FIXNUM),
Type::Flonum => Some(RUBY_T_FLOAT),
Type::TArray | Type::CArray => Some(RUBY_T_ARRAY),
Type::THash | Type::CHash => Some(RUBY_T_HASH),
Type::ImmSymbol => Some(RUBY_T_SYMBOL),
Type::TString | Type::CString => Some(RUBY_T_STRING),
Type::Unknown | Type::UnknownImm | Type::UnknownHeap => None,
Type::BlockParamProxy => None,
}
}
/// Returns an Option with the class if it is known, otherwise None
pub fn known_class(&self) -> Option<VALUE> {
unsafe {
match self {
Type::Nil => Some(rb_cNilClass),
Type::True => Some(rb_cTrueClass),
Type::False => Some(rb_cFalseClass),
Type::Fixnum => Some(rb_cInteger),
Type::Flonum => Some(rb_cFloat),
Type::ImmSymbol => Some(rb_cSymbol),
Type::CArray => Some(rb_cArray),
Type::CHash => Some(rb_cHash),
Type::CString => Some(rb_cString),
_ => None,
}
}
}
/// Returns an Option with the exact value if it is known, otherwise None
#[allow(unused)] // not yet used
pub fn known_exact_value(&self) -> Option<VALUE> {
match self {
Type::Nil => Some(Qnil),
Type::True => Some(Qtrue),
Type::False => Some(Qfalse),
_ => None,
}
}
/// Returns an Option boolean representing whether the value is truthy if known, otherwise None
pub fn known_truthy(&self) -> Option<bool> {
match self {
Type::Nil => Some(false),
Type::False => Some(false),
Type::UnknownHeap => Some(true),
Type::Unknown | Type::UnknownImm => None,
_ => Some(true)
}
}
/// Returns an Option boolean representing whether the value is equal to nil if known, otherwise None
pub fn known_nil(&self) -> Option<bool> {
match (self, self.known_truthy()) {
(Type::Nil, _) => Some(true),
(Type::False, _) => Some(false), // Qfalse is not nil
(_, Some(true)) => Some(false), // if truthy, can't be nil
(_, _) => None // otherwise unknown
}
}
/// Compute a difference between two value types
pub fn diff(self, dst: Self) -> TypeDiff {
// Perfect match, difference is zero
if self == dst {
return TypeDiff::Compatible(0);
}
// Any type can flow into an unknown type
if dst == Type::Unknown {
return TypeDiff::Compatible(1);
}
// A CArray is also a TArray.
if self == Type::CArray && dst == Type::TArray {
return TypeDiff::Compatible(1);
}
// A CHash is also a THash.
if self == Type::CHash && dst == Type::THash {
return TypeDiff::Compatible(1);
}
// A CString is also a TString.
if self == Type::CString && dst == Type::TString {
return TypeDiff::Compatible(1);
}
// Specific heap type into unknown heap type is imperfect but valid
if self.is_heap() && dst == Type::UnknownHeap {
return TypeDiff::Compatible(1);
}
// Specific immediate type into unknown immediate type is imperfect but valid
if self.is_imm() && dst == Type::UnknownImm {
return TypeDiff::Compatible(1);
}
// Incompatible types
return TypeDiff::Incompatible;
}
/// Upgrade this type into a more specific compatible type
/// The new type must be compatible and at least as specific as the previously known type.
fn upgrade(&mut self, new_type: Self) {
// We can only upgrade to a type that is more specific
assert!(new_type.diff(*self) != TypeDiff::Incompatible);
*self = new_type;
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum TypeDiff {
// usize == 0: Same type
// usize >= 1: Different but compatible. The smaller, the more compatible.
Compatible(usize),
Incompatible,
}
#[derive(Copy, Clone, Eq, Hash, PartialEq, Debug)]
pub enum TempMapping {
MapToStack(Type),
MapToSelf,
MapToLocal(u8),
}
impl Default for TempMapping {
fn default() -> Self {
TempMapping::MapToStack(Type::default())
}
}
impl TempMapping {
/// Return TempMapping without type information in MapToStack
pub fn without_type(&self) -> TempMapping {
match self {
MapToStack(_) => TempMapping::MapToStack(Type::default()),
_ => *self,
}
}
}
// Operand to a YARV bytecode instruction
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum YARVOpnd {
// The value is self
SelfOpnd,
// Temporary stack operand with stack index
StackOpnd(u8),
}
impl From<Opnd> for YARVOpnd {
fn from(value: Opnd) -> Self {
match value {
Opnd::Stack { idx, .. } => StackOpnd(idx.try_into().unwrap()),
_ => unreachable!("{:?} cannot be converted to YARVOpnd", value)
}
}
}
/// Number of registers that can be used for stack temps or locals
pub const MAX_MAPPED_REGS: usize = 5;
/// A stack slot or a local variable. u8 represents the index of it (<= 8).
#[derive(Copy, Clone, Eq, Hash, PartialEq, Debug)]
pub enum RegOpnd {
Stack(u8),
Local(u8),
}
/// RegMappings manages a set of registers used for stack temps and locals.
/// Each element of the array represents each of the registers.
/// If an element is Some, the stack temp or the local uses a register.
///
/// Note that Opnd::InsnOut uses a separate set of registers at the moment.
#[derive(Copy, Clone, Default, Eq, Hash, PartialEq)]
pub struct RegMapping([Option<RegOpnd>; MAX_MAPPED_REGS]);
impl RegMapping {
/// Return the index of the register for a given operand if allocated.
pub fn get_reg(&self, opnd: RegOpnd) -> Option<usize> {
self.0.iter().enumerate()
.find(|(_, ®_opnd)| reg_opnd == Some(opnd))
.map(|(reg_idx, _)| reg_idx)
}
/// Set a given operand to the register at a given index.
pub fn set_reg(&mut self, opnd: RegOpnd, reg_idx: usize) {
assert!(self.0[reg_idx].is_none());
self.0[reg_idx] = Some(opnd);
}
/// Allocate a register for a given operand if available.
/// Return true if self is updated.
pub fn alloc_reg(&mut self, opnd: RegOpnd) -> bool {
// If a given opnd already has a register, skip allocation.
if self.get_reg(opnd).is_some() {
return false;
}
// If the index is too large to encode with with 3 bits, give up.
match opnd {
RegOpnd::Stack(stack_idx) => if stack_idx >= MAX_CTX_TEMPS as u8 {
return false;
}
RegOpnd::Local(local_idx) => if local_idx >= MAX_CTX_LOCALS as u8 {
return false;
}
};
// Allocate a register if available.
if let Some(reg_idx) = self.find_unused_reg(opnd) {
self.0[reg_idx] = Some(opnd);
return true;
}
false
}
/// Deallocate a register for a given operand if in use.
/// Return true if self is updated.
pub fn dealloc_reg(&mut self, opnd: RegOpnd) -> bool {
for reg_opnd in self.0.iter_mut() {
if *reg_opnd == Some(opnd) {
*reg_opnd = None;
return true;
}
}
false
}
/// Find an available register and return the index of it.
fn find_unused_reg(&self, opnd: RegOpnd) -> Option<usize> {
let num_regs = get_option!(num_temp_regs);
if num_regs == 0 {
return None;
}
assert!(num_regs <= MAX_MAPPED_REGS);
// If the default index for the operand is available, use that to minimize
// discrepancies among Contexts.
let default_idx = match opnd {
RegOpnd::Stack(stack_idx) => stack_idx.as_usize() % num_regs,
RegOpnd::Local(local_idx) => num_regs - (local_idx.as_usize() % num_regs) - 1,
};
if self.0[default_idx].is_none() {
return Some(default_idx);
}
// If not, pick any other available register. Like default indexes, prefer
// lower indexes for Stack, and higher indexes for Local.
let mut index_temps = self.0.iter().enumerate();
match opnd {
RegOpnd::Stack(_) => index_temps.find(|(_, reg_opnd)| reg_opnd.is_none()),
RegOpnd::Local(_) => index_temps.rev().find(|(_, reg_opnd)| reg_opnd.is_none()),
}.map(|(index, _)| index)
}
/// Return a vector of RegOpnds that have an allocated register
pub fn get_reg_opnds(&self) -> Vec<RegOpnd> {
self.0.iter().filter_map(|®_opnd| reg_opnd).collect()
}
/// Return TypeDiff::Compatible(diff) if dst has a mapping that can be made by moving registers
/// in self `diff` times. TypeDiff::Incompatible if they have different things in registers.
pub fn diff(&self, dst: RegMapping) -> TypeDiff {
let src_opnds = self.get_reg_opnds();
let dst_opnds = dst.get_reg_opnds();
if src_opnds.len() != dst_opnds.len() {
return TypeDiff::Incompatible;
}
let mut diff = 0;
for ®_opnd in src_opnds.iter() {
match (self.get_reg(reg_opnd), dst.get_reg(reg_opnd)) {
(Some(src_idx), Some(dst_idx)) => if src_idx != dst_idx {
diff += 1;
}
_ => return TypeDiff::Incompatible,
}
}
TypeDiff::Compatible(diff)
}
}
impl fmt::Debug for RegMapping {
/// Print `[None, ...]` instead of the default `RegMappings([None, ...])`
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{:?}", self.0)
}
}
/// Maximum value of the chain depth (should fit in 5 bits)
const CHAIN_DEPTH_MAX: u8 = 0b11111; // 31
/// Code generation context
/// Contains information we can use to specialize/optimize code
#[derive(Copy, Clone, Default, Eq, Hash, PartialEq, Debug)]
pub struct Context {
// Number of values currently on the temporary stack
stack_size: u8,
// Offset of the JIT SP relative to the interpreter SP
// This represents how far the JIT's SP is from the "real" SP
sp_offset: i8,
/// Which stack temps or locals are in a register
reg_mapping: RegMapping,
// Depth of this block in the sidechain (eg: inline-cache chain)
// 6 bits, max 63
chain_depth: u8,
// Whether this code is the target of a JIT-to-JIT Ruby return ([Self::is_return_landing])
is_return_landing: bool,
// Whether the compilation of this code has been deferred ([Self::is_deferred])
is_deferred: bool,
// Type we track for self
self_type: Type,
// Local variable types we keep track of
local_types: [Type; MAX_CTX_LOCALS],
// Temp mapping type/local_idx we track
temp_mapping: [TempMapping; MAX_CTX_TEMPS],
/// A pointer to a block ISEQ supplied by the caller. 0 if not inlined.
inline_block: Option<IseqPtr>,
}
#[derive(Clone)]
pub struct BitVector {
// Flat vector of bytes to write into
bytes: Vec<u8>,
// Number of bits taken out of bytes allocated
num_bits: usize,
}
impl BitVector {
pub fn new() -> Self {
Self {
bytes: Vec::with_capacity(4096),
num_bits: 0,
}
}
#[allow(unused)]
pub fn num_bits(&self) -> usize {
self.num_bits
}
// Total number of bytes taken
#[allow(unused)]
pub fn num_bytes(&self) -> usize {
(self.num_bits / 8) + if (self.num_bits % 8) != 0 { 1 } else { 0 }
}
// Write/append an unsigned integer value
fn push_uint(&mut self, mut val: u64, mut num_bits: usize) {
assert!(num_bits <= 64);
// Mask out bits above the number of bits requested
let mut val_bits = val;
if num_bits < 64 {
val_bits &= (1 << num_bits) - 1;
assert!(val == val_bits);
}
// Number of bits encoded in the last byte
let rem_bits = self.num_bits % 8;
// Encode as many bits as we can in this last byte
if rem_bits != 0 {
let num_enc = std::cmp::min(num_bits, 8 - rem_bits);
let bit_mask = (1 << num_enc) - 1;
let frac_bits = (val & bit_mask) << rem_bits;
let frac_bits: u8 = frac_bits.try_into().unwrap();
let last_byte_idx = self.bytes.len() - 1;
self.bytes[last_byte_idx] |= frac_bits;
self.num_bits += num_enc;
num_bits -= num_enc;
val >>= num_enc;
}
// While we have bits left to encode
while num_bits > 0 {
// Grow with a 1.2x growth factor instead of 2x
assert!(self.num_bits % 8 == 0);
let num_bytes = self.num_bits / 8;
if num_bytes == self.bytes.capacity() {
self.bytes.reserve_exact(self.bytes.len() / 5);
}
let bits = val & 0xFF;
let bits: u8 = bits.try_into().unwrap();
self.bytes.push(bits);
let bits_to_encode = std::cmp::min(num_bits, 8);
self.num_bits += bits_to_encode;
num_bits -= bits_to_encode;
val >>= bits_to_encode;
}
}
fn push_u8(&mut self, val: u8) {
self.push_uint(val as u64, 8);
}
fn push_u5(&mut self, val: u8) {
assert!(val <= 0b11111);
self.push_uint(val as u64, 5);
}
fn push_u4(&mut self, val: u8) {
assert!(val <= 0b1111);
self.push_uint(val as u64, 4);
}
fn push_u3(&mut self, val: u8) {
assert!(val <= 0b111);
self.push_uint(val as u64, 3);
}
fn push_u2(&mut self, val: u8) {
assert!(val <= 0b11);
self.push_uint(val as u64, 2);
}
fn push_u1(&mut self, val: u8) {
assert!(val <= 0b1);
self.push_uint(val as u64, 1);
}
fn push_bool(&mut self, val: bool) {
self.push_u1(if val { 1 } else { 0 });
}
// Push a context encoding opcode
fn push_op(&mut self, op: CtxOp) {
self.push_u4(op as u8);
}
// Read a uint value at a given bit index
// The bit index is incremented after the value is read
fn read_uint(&self, bit_idx: &mut usize, mut num_bits: usize) -> u64 {
let start_bit_idx = *bit_idx;
let mut cur_idx = *bit_idx;
// Read the bits in the first byte
let bit_mod = cur_idx % 8;
let bits_in_byte = self.bytes[cur_idx / 8] >> bit_mod;
let num_bits_in_byte = std::cmp::min(num_bits, 8 - bit_mod);
cur_idx += num_bits_in_byte;
num_bits -= num_bits_in_byte;
let mut out_bits = (bits_in_byte as u64) & ((1 << num_bits_in_byte) - 1);
// While we have bits left to read
while num_bits > 0 {
let num_bits_in_byte = std::cmp::min(num_bits, 8);
assert!(cur_idx % 8 == 0);
let byte = self.bytes[cur_idx / 8] as u64;
let bits_in_byte = byte & ((1 << num_bits) - 1);
out_bits |= bits_in_byte << (cur_idx - start_bit_idx);
// Move to the next byte/offset
cur_idx += num_bits_in_byte;
num_bits -= num_bits_in_byte;
}
// Update the read index
*bit_idx = cur_idx;
out_bits
}
fn read_u8(&self, bit_idx: &mut usize) -> u8 {
self.read_uint(bit_idx, 8) as u8
}
fn read_u5(&self, bit_idx: &mut usize) -> u8 {
self.read_uint(bit_idx, 5) as u8
}
fn read_u4(&self, bit_idx: &mut usize) -> u8 {
self.read_uint(bit_idx, 4) as u8
}
fn read_u3(&self, bit_idx: &mut usize) -> u8 {
self.read_uint(bit_idx, 3) as u8
}
fn read_u2(&self, bit_idx: &mut usize) -> u8 {
self.read_uint(bit_idx, 2) as u8
}
fn read_u1(&self, bit_idx: &mut usize) -> u8 {
self.read_uint(bit_idx, 1) as u8
}
fn read_bool(&self, bit_idx: &mut usize) -> bool {
self.read_u1(bit_idx) != 0
}
fn read_op(&self, bit_idx: &mut usize) -> CtxOp {
unsafe { std::mem::transmute(self.read_u4(bit_idx)) }
}
}
impl fmt::Debug for BitVector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// We print the higher bytes first
for (idx, byte) in self.bytes.iter().enumerate().rev() {
write!(f, "{:08b}", byte)?;
// Insert a separator between each byte
if idx > 0 {
write!(f, "|")?;
}
}
Ok(())
}
}
#[cfg(test)]
mod bitvector_tests {
use super::*;
#[test]
fn write_3() {
let mut arr = BitVector::new();
arr.push_uint(3, 2);
assert!(arr.read_uint(&mut 0, 2) == 3);
}
#[test]
fn write_11() {
let mut arr = BitVector::new();
arr.push_uint(1, 1);
arr.push_uint(1, 1);
assert!(arr.read_uint(&mut 0, 2) == 3);
}
#[test]
fn write_11_overlap() {
let mut arr = BitVector::new();
arr.push_uint(0, 7);
arr.push_uint(3, 2);
arr.push_uint(1, 1);
//dbg!(arr.read_uint(7, 2));
assert!(arr.read_uint(&mut 7, 2) == 3);
}
#[test]
fn write_ff_0() {
let mut arr = BitVector::new();
arr.push_uint(0xFF, 8);
assert!(arr.read_uint(&mut 0, 8) == 0xFF);
}
#[test]
fn write_ff_3() {
// Write 0xFF at bit index 3
let mut arr = BitVector::new();
arr.push_uint(0, 3);
arr.push_uint(0xFF, 8);
assert!(arr.read_uint(&mut 3, 8) == 0xFF);
}
#[test]
fn write_ff_sandwich() {
// Write 0xFF sandwiched between zeros
let mut arr = BitVector::new();
arr.push_uint(0, 3);
arr.push_u8(0xFF);
arr.push_uint(0, 3);
assert!(arr.read_uint(&mut 3, 8) == 0xFF);
}
#[test]
fn write_read_u32_max() {
let mut arr = BitVector::new();
arr.push_uint(0xFF_FF_FF_FF, 32);
assert!(arr.read_uint(&mut 0, 32) == 0xFF_FF_FF_FF);
}
#[test]
fn write_read_u32_max_64b() {
let mut arr = BitVector::new();
arr.push_uint(0xFF_FF_FF_FF, 64);
assert!(arr.read_uint(&mut 0, 64) == 0xFF_FF_FF_FF);
}
#[test]
fn write_read_u64_max() {
let mut arr = BitVector::new();
arr.push_uint(u64::MAX, 64);
assert!(arr.read_uint(&mut 0, 64) == u64::MAX);
}
#[test]
fn encode_default() {
let mut bits = BitVector::new();
let ctx = Context::default();
let start_idx = ctx.encode_into(&mut bits);
assert!(start_idx == 0);
assert!(bits.num_bits() > 0);
assert!(bits.num_bytes() > 0);
// Make sure that the round trip matches the input
let ctx2 = Context::decode_from(&bits, 0);
assert!(ctx2 == ctx);
}
#[test]
fn encode_default_2x() {
let mut bits = BitVector::new();
let ctx0 = Context::default();
let idx0 = ctx0.encode_into(&mut bits);
let mut ctx1 = Context::default();
ctx1.reg_mapping = RegMapping([Some(RegOpnd::Stack(0)), None, None, None, None]);
let idx1 = ctx1.encode_into(&mut bits);
// Make sure that we can encode two contexts successively
let ctx0_dec = Context::decode_from(&bits, idx0);
let ctx1_dec = Context::decode_from(&bits, idx1);
assert!(ctx0_dec == ctx0);
assert!(ctx1_dec == ctx1);
}
#[test]
fn regress_reg_mapping() {
let mut bits = BitVector::new();
let mut ctx = Context::default();
ctx.reg_mapping = RegMapping([Some(RegOpnd::Stack(0)), None, None, None, None]);
ctx.encode_into(&mut bits);
let b0 = bits.read_u1(&mut 0);
assert!(b0 == 1);
// Make sure that the round trip matches the input
let ctx2 = Context::decode_from(&bits, 0);
assert!(ctx2 == ctx);
}
}
// Context encoding opcodes (4 bits)
#[derive(Debug, Copy, Clone)]
#[repr(u8)]
enum CtxOp {
// Self type (4 bits)
SetSelfType = 0,
// Local idx (3 bits), temp type (4 bits)
SetLocalType,
// Map stack temp to self with known type
// Temp idx (3 bits), known type (4 bits)
SetTempType,
// Map stack temp to a local variable
// Temp idx (3 bits), local idx (3 bits)
MapTempLocal,
// Map a stack temp to self
// Temp idx (3 bits)
MapTempSelf,
// Set inline block pointer (8 bytes)
SetInlineBlock,
// End of encoding
EndOfCode,
}
// Number of entries in the context cache
const CTX_ENCODE_CACHE_SIZE: usize = 1024;
const CTX_DECODE_CACHE_SIZE: usize = 1024;
// Cache of the last contexts encoded/decoded
// Empirically this saves a few percent of memory and speeds up compilation
// We can experiment with varying the size of this cache
pub type CtxEncodeCache = [(Context, u32); CTX_ENCODE_CACHE_SIZE];
static mut CTX_ENCODE_CACHE: Option<Box<CtxEncodeCache>> = None;
// Cache of the last contexts encoded/decoded
// This speeds up compilation
pub type CtxDecodeCache = [(Context, u32); CTX_DECODE_CACHE_SIZE];
static mut CTX_DECODE_CACHE: Option<Box<CtxDecodeCache>> = None;
// Size of the context cache in bytes
pub const CTX_ENCODE_CACHE_BYTES: usize = std::mem::size_of::<CtxEncodeCache>();
pub const CTX_DECODE_CACHE_BYTES: usize = std::mem::size_of::<CtxDecodeCache>();
impl Context {
// Encode a context into the global context data, or return
// a cached previously encoded offset if one is found
pub fn encode(&self) -> u32 {
incr_counter!(num_contexts_encoded);
if *self == Context::default() {
incr_counter!(context_cache_hits);
return 0;
}
if let Some(idx) = Self::encode_cache_get(self) {
incr_counter!(context_cache_hits);
debug_assert!(Self::decode(idx) == *self);
return idx;
}
let context_data = CodegenGlobals::get_context_data();
// Make sure we don't use offset 0 because
// it's is reserved for the default context
if context_data.num_bits() == 0 {
context_data.push_u1(0);
}
let idx = self.encode_into(context_data);
let idx: u32 = idx.try_into().unwrap();
// Save this offset into the cache
Self::encode_cache_set(self, idx);
Self::decode_cache_set(self, idx);
// In debug mode, check that the round-trip decoding always matches
debug_assert!(Self::decode(idx) == *self);
idx
}
pub fn decode(start_idx: u32) -> Context {
if start_idx == 0 {
return Context::default();
};
if let Some(ctx) = Self::decode_cache_get(start_idx) {
return ctx;
}
let context_data = CodegenGlobals::get_context_data();
let ctx = Self::decode_from(context_data, start_idx as usize);
Self::encode_cache_set(&ctx, start_idx);
Self::decode_cache_set(&ctx, start_idx);
ctx
}
// Store an entry in a cache of recently encoded/decoded contexts for encoding
fn encode_cache_set(ctx: &Context, idx: u32)
{
// Compute the hash for this context
let mut hasher = DefaultHasher::new();
ctx.hash(&mut hasher);
let ctx_hash = hasher.finish() as usize;
unsafe {
// Lazily initialize the context cache
if CTX_ENCODE_CACHE == None {
// Here we use the vec syntax to avoid allocating the large table on the stack,
// as this can cause a stack overflow
let tbl = vec![(Context::default(), 0); CTX_ENCODE_CACHE_SIZE].into_boxed_slice().try_into().unwrap();
CTX_ENCODE_CACHE = Some(tbl);
}
// Write a cache entry for this context
let cache = CTX_ENCODE_CACHE.as_mut().unwrap();
cache[ctx_hash % CTX_ENCODE_CACHE_SIZE] = (*ctx, idx);
}
}
// Store an entry in a cache of recently encoded/decoded contexts for decoding
fn decode_cache_set(ctx: &Context, idx: u32) {
unsafe {
// Lazily initialize the context cache
if CTX_DECODE_CACHE == None {
// Here we use the vec syntax to avoid allocating the large table on the stack,
// as this can cause a stack overflow
let tbl = vec![(Context::default(), 0); CTX_ENCODE_CACHE_SIZE].into_boxed_slice().try_into().unwrap();
CTX_DECODE_CACHE = Some(tbl);
}
// Write a cache entry for this context
let cache = CTX_DECODE_CACHE.as_mut().unwrap();
cache[idx as usize % CTX_ENCODE_CACHE_SIZE] = (*ctx, idx);
}
}
// Lookup the context in a cache of recently encoded/decoded contexts for encoding
fn encode_cache_get(ctx: &Context) -> Option<u32>
{
// Compute the hash for this context
let mut hasher = DefaultHasher::new();
ctx.hash(&mut hasher);
let ctx_hash = hasher.finish() as usize;
unsafe {
if CTX_ENCODE_CACHE == None {
return None;
}
let cache = CTX_ENCODE_CACHE.as_mut().unwrap();